ItemTemplate和ItemPanelTemplate有什么区别?

在WPF
Listbox
中,我对这两个概念感到困惑:
ItemTemplate
ItemsPanelTemplate
有人可以解释一下吗? 谢谢 约翰     
已邀请:
让我试着通过例子解释一下:
<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>
结果如下:
ItemTemplate
确定列表中每个项目的布局。另一方面,
ItemsPanel
是包含各个项目的面板。鉴于上述定义,可视化树将类似于此:
<StackPanel>
  <Border>
    <TextBlock Text="Alpha"/>
  </Border>
  <Border>
    <TextBlock Text="Beta"/>
  </Border>
  ....
</StackPanel>
    
ItemTemplate用于指定用于在ListBox中呈现项目的DataTemplate。 ItemPanelTemplate用于指定用于排列ListBox子项的面板。 例如,如果ListBox绑定到ObservableCollection,则必须指定DataTemplate以告诉它如何呈现每个Person对象。
<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>
这将垂直排列每个项目,因为ListBox默认使用StackPanel。如果要更改此行为,请使用ItemPanelTemplate属性:
<ListBox>
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel Orientation="Horizontal"/>
    </ItemsPanelTemplate>            
  </ListBox.ItemsPanel>
</ListBox>
您甚至可以将StackPanel更改为任何其他面板(例如WrapPanel)。     

要回复问题请先登录注册