In WPF Listbox
, I'm confused with these 2 notions:
ItemTemplate
and ItemsPanelTemplate
Can someone explain me more?
Thanks John
You use the ItemTemplate to specify the visualization of the data objects. If your ItemsControl is bound to a collection object and you do not provide specific display instructions using a DataTemplate, the resulting UI of each item is a string representation of each object in the underlying collection.
ItemsPanelTemplate enables you to customize the panel, which defines the layout of items in ItemControls like ListBox and ListView. Every ItemControl has its default panel. For example, Default panel for ListBox is VirtualizingStackPanel.
Let me try to explain this by example:
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Background="SteelBlue" Padding="5" BorderBrush="Black"
BorderThickness="1" Margin="0,2">
<TextBlock Text="{Binding}"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Background="DarkKhaki"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
And the result:
The ItemTemplate
determines the layout of each item in the list. On the other hand the ItemsPanel
is the panel that will contain the individual items. Given the above definition the visual tree will be something similar to this:
<StackPanel>
<Border>
<TextBlock Text="Alpha"/>
</Border>
<Border>
<TextBlock Text="Beta"/>
</Border>
....
</StackPanel>
ItemTemplate is used to specify a DataTemplate used to render the item in your ListBox. ItemPanelTemplate is used to specify the panel used to arrange the children of your ListBox.
For example, if your ListBox is bound to an ObservableCollection you must specify a DataTemplate to tell it how to render each Person object.
<ListBox ItemsSource={Binding Persons}>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text={Binding FirstName}/>
<TextBlock Text={Binding LastName}/>
<TextBlock Text={Binding Age}/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
That will arrange each item vertically because ListBox used a StackPanel by default. If you want to change this behaviour, used the ItemPanelTemplate property:
<ListBox>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
You can even change the StackPanel to any other panel (WrapPanel for example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With