ItemTemplate和ItemPanelTemplate有什么区别?

use*_*547 14 wpf itemtemplate itemspaneltemplate

在WPF中Listbox,我很困惑与这些概念2: ItemTemplateItemsPanelTemplate 一个人能更给我解释一下?

谢谢约翰

Mar*_*age 21

让我试着通过例子解释一下:

<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>
Run Code Online (Sandbox Code Playgroud)

结果如下:

WPF ListBox模板示例

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

<StackPanel>
  <Border>
    <TextBlock Text="Alpha"/>
  </Border>
  <Border>
    <TextBlock Text="Beta"/>
  </Border>
  ....
</StackPanel>
Run Code Online (Sandbox Code Playgroud)


jap*_*apf 11

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>
Run Code Online (Sandbox Code Playgroud)

这将垂直排列每个项目,因为ListBox默认使用StackPanel.如果要更改此行为,请使用ItemPanelTemplate属性:

<ListBox>
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel Orientation="Horizontal"/>
    </ItemsPanelTemplate>            
  </ListBox.ItemsPanel>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

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