What is the difference between ItemTemplate and ItemPanelTemplate?
Asked Answered
M

2

16

In WPF Listbox, I'm confused with these 2 notions: ItemTemplate and ItemsPanelTemplate Can someone explain me more?

Thanks John

Mincey answered 11/9, 2009 at 7:40 Comment(0)
G
26

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:

WPF ListBox templates example

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>
Grammalogue answered 11/9, 2009 at 8:14 Comment(0)
F
13

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).

Fubsy answered 11/9, 2009 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.