【问题标题】:What is the difference between ItemTemplate and ItemPanelTemplate?ItemTemplate 和 ItemPanelTemplate 有什么区别?
【发布时间】:2009-09-11 07:40:21
【问题描述】:

在 WPF Listbox 中,我对以下两个概念感到困惑: ItemTemplateItemsPanelTemplate 谁能给我解释一下?

谢谢 约翰

【问题讨论】:

    标签: wpf itemtemplate itemspaneltemplate


    【解决方案1】:

    让我试着举例说明一下:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-02
        • 2011-12-12
        • 2010-09-16
        • 2012-03-14
        • 2012-02-06
        • 2011-02-25
        • 2011-11-22
        • 2015-03-26
        相关资源
        最近更新 更多