WPF ListBox可以横向排列其项目

66

我正在尝试编写一个WPF应用程序,用于显示从选择中获取的图像。 我希望在窗口顶部显示所有可用图像的横幅,并在主窗口中显示主选定的图像以进行进一步处理。

如果我想要列表出现在窗口左侧,垂直地显示图像,则可以使用数据绑定来实现这一点。

    <ListBox 
        Name="m_listBox"
        IsSynchronizedWithCurrentItem="True"
        ItemsSource="{Binding}"            
        >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding}" Width="60" Stretch="Uniform" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

有没有直接的方法可以使这个垂直的变成水平的?

解决方案的主要要求是:

  • 使用数据绑定填充项目。
  • 用户仅需单击即可更改所选项目。
3个回答

135

WrapPanel

 <ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel IsItemsHost="True" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBoxItem>listbox item 1</ListBoxItem>
    <ListBoxItem>listbox item 2</ListBoxItem>
    <ListBoxItem>listbox item 3</ListBoxItem>
    <ListBoxItem>listbox item 4</ListBoxItem>
    <ListBoxItem>listbox item 5</ListBoxItem>
</ListBox>

WPF教程


44
StackPanel 的 Orientation 属性设置为 "Horizontal"。 - Nir
2
StackPanel会是更好的解决方案,就像Nir所说的那样。 - Bryan Anderson
1
谢谢!是的,具有水平方向的 StackPanel 是更好的选择。 - KV Prajapati
2
代表 Andrew Megs 给你点赞。他发现你的代码非常有用,但不想给你“虚拟网络积分”。 - Taekahn

28

ListBox控件默认的ItemsPanelVirtualizingStackPanel,所以如果你想要控件的正常默认体验,但希望它水平布局,你应该指定这个(并更改方向)。

示例:

<ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel IsItemsHost="True" Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

2

这是一个StackPanel的例子。 使用Mvvm绑定实现水平面包屑导航。

 <ItemsControl
            x:Name="tStack"
            Grid.Row="1"
            Grid.Column="0"
            Height="40"
            Background="Red"
            ItemsSource="{Binding BreadCrumbs}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button
                        Margin="5"
                        CommandParameter="{Binding .}"
                        Command="{Binding BreadcrumbClickCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}, Path=DataContext.BreadcrumbClickCommand}"
                        Content="{Binding Name}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接