【问题标题】:Showing a collection of items inside of a ItemsControl horizontally水平显示 ItemsControl 内的项目集合
【发布时间】:2025-12-29 00:55:12
【问题描述】:

这是 XAML 标记:

        <ScrollViewer Grid.Column="1" Grid.Row="2" HorizontalScrollBarVisibility="Disabled" Width="990">
            <StackPanel Margin="50 0 0 40">                    
                <ItemsControl x:Name="streamList" ItemsSource="{Binding StreamInformations}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Margin="10" Orientation="Horizontal" >
                                <StackPanel Orientation="Horizontal">
                                    <Image Source="{Binding ImageUrl}" Height="60" />
                                    <StackPanel Margin="10 0 0 0" VerticalAlignment="Center">
                                        <TextBlock Foreground="Black" Text="{Binding ChannelName}" FontSize="12" />
                                        <TextBlock Foreground="#999" Text="{Binding PlayerName}" FontSize="10" />
                                        <TextBlock Foreground="#999" Text="{Binding ViewCount}" FontSize="10" />
                                    </StackPanel>                                        
                                </StackPanel>                                   
                            </StackPanel>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </ScrollViewer>

这就是它的外观:

我希望这些项目水平显示并在到达 StackPanel 边缘时向下流动。

目前看来,我的 DataContext 集合中的每个项目都在创建自己的 StackPanel,所以这不是我想要的。

有什么建议吗?

【问题讨论】:

  • 如果这个问题的唯一答案对你有用,那么接受它。如果它没有提供反馈,说明为什么它不适用于您的问题。答案已经适用于包括我自己在内的许多其他人。

标签: wpf xaml panel datatemplate itemscontrol


【解决方案1】:

如果你把ItemsPanel模板改成WrapPanel或者水平StackPanel,都可以达到你想要的效果...

<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <!--other stuff here--> 
    </ItemsControl.ItemTemplate>
</ItemsControl>

在这个 sn-p 中,ItemsPanel 设置为水平方向的 WrapPanel。 ItemTemplate 将包括您已经拥有的绑定和样式...

【讨论】: