ItemTemplate和ItemPanelTemplate有什么区别?

16
在 WPF 的 Listbox 中,我对这两个概念感到困惑:ItemTemplate 和 ItemsPanelTemplate。能否有人给我更多解释?谢谢,John。
回答:
在 WPF 的 Listbox 中,ItemTemplate 定义了如何呈现 Listbox 中的每个数据项,而 ItemsPanelTemplate 则定义了如何排列这些数据项。
2个回答

26

让我通过一个例子来解释:

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

结果如下:

WPF ListBox templates example

ItemTemplate决定了列表中每个项目的布局。另一方面,ItemsPanel是包含各个项目的面板。根据上述定义,可视化树将类似于此:

<StackPanel>
  <Border>
    <TextBlock Text="Alpha"/>
  </Border>
  <Border>
    <TextBlock Text="Beta"/>
  </Border>
  ....
</StackPanel>

13

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 属性:

这将.vertical地排列每个.item,因为ListBox默认使用StackPanel。如果您想更改此行为,请使用ItemPanelTemplate属性:

<ListBox>
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel Orientation="Horizontal"/>
    </ItemsPanelTemplate>            
  </ListBox.ItemsPanel>
</ListBox>

您甚至可以将StackPanel更改为任何其他面板(例如WrapPanel)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接