tags:

views:

231

answers:

2

In WPF Listbox, I'm confused with this 2 notions : ItemTemplate and ItemPanelTemplate Can someone explain me more ? Thanks John

A: 

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

Jalfp
+2  A: 
Martin Liversage