#400 – Using a WrapPanel as the Items Panel for a ListBox
October 4, 2011 2 Comments
The ItemsPanel property of a ListBox specifies the template that defines the panel used to contain the elements of the ListBox. You can override the normal vertically stacked layout of a ListBox by defining your own template.
If you set the ItemsPanel template to contain a WrapPanel, the ListBox will show its child elements left to right, wrapping to the next row when each row fills up.
In the example below, we bind a ListBox to a list of movies, specify an ItemTemplate that dictates how each item appears, and then specify a template for the ItemsPanel that contains a 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>
Notice that the layout changes as we resize the parent window.



