ListBox 的ItemsPanel 属性可以指定定义显示各子项的面板的模板。你可以通过定义自己的模板重写ListBox 常见的垂直堆叠式布局。
如果你设置了ItemsPanel 模板为WrapPanel,ListBox 将会有WrapPanel的特性。
在下面的例子中,我们将上一篇中的ListBox 稍作修改。指定ItemsPanel 包含一个WrapPanel。
-
<Grid>
-
<ListBox ItemsSource="{Binding MovieList}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
-
<ListBox.ItemTemplate>
-
<DataTemplate>
-
<StackPanel Orientation="Vertical">
-
<Image Source="{Binding Image}" Stretch="None"/>
-
<Label Content="{Binding TitleWithYear}"/>
-
</StackPanel>
-
</DataTemplate>
-
</ListBox.ItemTemplate>
-
<ListBox.ItemsPanel>
-
<ItemsPanelTemplate>
-
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
-
</ItemsPanelTemplate>
-
</ListBox.ItemsPanel>
-
</ListBox>
-
</Grid>
可以看到,将ItemsPanel 设置为WrapPanel后,改变窗口的大小,ListBox显示会自动根据窗口大小换行。