WPF:带滚动条的 ListBoxItem

WPF: ListBoxItem with scroll bar

是否可以有 ListBox(默认包含 ScrollViewer)和 ListBoxItemScrollViewer? 我想实现下一个视图:

而且这个ListBox应该也支持虚拟化。 (我知道如何启用它,我只是想知道如果我使用 2 个滚动查看器它会起作用吗?)

更新: 我需要使用 ListBox.ItemTemplate,因为我绑定了 ItemsSource.

感谢提示。

简单。 (我给了你三种方法,一个一定是对的!)

通过Xaml:

    <ListBox x:Name="ListBoxControl" HorizontalAlignment="Left" Height="320" VerticalAlignment="Top" Width="520">
        <ListBoxItem Width="520">
            <ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Disabled">
                <Label Content="My Name is KidCode. This is a reeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeaaaaaaaaaaaaaaaaaaaaaaaaly long comment."/>
            </ScrollViewer>
        </ListBoxItem>
    </ListBox>

来自 C#:

namespace StackExchange
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var lbv = new ListBoxItemSV()
            {
                Height = 40,
                Width= 520,
                Background = Brushes.Blue
            };
            ListBoxControl.Items.Add(lbv);
        }

        public class ListBoxItemSV : ListBoxItem
        {
            ScrollViewer sv = new ScrollViewer()
            {
                HorizontalScrollBarVisibility = ScrollBarVisibility.Visible,
                VerticalScrollBarVisibility = ScrollBarVisibility.Hidden
            };
            Label lbl = new Label()
            {
                Content = "A really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really long name."
            };

            public ListBoxItemSV()
            {
                sv.Content = lbl;
                this.Content = sv;
            }
        }
    }
}

结果如下:(我添加了一个简短的评论只是为了让您看到其中的区别,您可以使滚动条一直移动,但这只是一个示例。)

如果你使用物品模板: (我从来没有这样做过,如果错了不要拍我!:))

XAML:

<ListBox x:Name="ListBoxTwo">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Disabled" Width="520">
                        <Label Content="{Binding}"/>
                    </ScrollViewer>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

隐藏代码:

    List<string> Mylist = new List<string>();
    Mylist.Add("Short Name");
    Mylist.Add("Another Short Name");
    Mylist.Add("A massively, hugely, giganticly, monstorously large name. (Its even bigger than than you think...............) ");

    ListBoxTwo.ItemsSource = Mylist;

输出: