ItemsControl.ItemTemplate 属性

定义

获取或设置用来显示每个项的 DataTemplate

public:
 property System::Windows::DataTemplate ^ ItemTemplate { System::Windows::DataTemplate ^ get(); void set(System::Windows::DataTemplate ^ value); };
[System.ComponentModel.Bindable(true)]
public System.Windows.DataTemplate ItemTemplate { get; set; }
[<System.ComponentModel.Bindable(true)>]
member this.ItemTemplate : System.Windows.DataTemplate with get, set
Public Property ItemTemplate As DataTemplate

属性值

DataTemplate

指定数据对象的可视化的 DataTemplate。 默认值为 null

属性

示例

以下示例演示如何创建 DataTemplate 内联。 指定 DataTemplate 每个数据项在一个中显示为三 TextBlockStackPanel元素。 在此示例中,数据对象是一 Task个名为 的类。 请注意,此模板中的每个 TextBlock 元素都绑定到类的属性 Task

<ListBox Width="400" Margin="10"
         ItemsSource="{Binding Source={StaticResource myTodoList}}">
   <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <TextBlock Text="{Binding Path=TaskName}" />
         <TextBlock Text="{Binding Path=Description}"/>
         <TextBlock Text="{Binding Path=Priority}"/>
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>

更常见的是在资源部分中定义一个 DataTemplate ,以便它可以是可重用的对象,如以下示例所示:

<Window.Resources>
<DataTemplate x:Key="myTaskTemplate">
  <StackPanel>
    <TextBlock Text="{Binding Path=TaskName}" />
    <TextBlock Text="{Binding Path=Description}"/>
    <TextBlock Text="{Binding Path=Priority}"/>
  </StackPanel>
</DataTemplate>
</Window.Resources>

现在可以将 myTaskTemplate 用作资源,如以下示例所示:

<ListBox Width="400" Margin="10"
         ItemsSource="{Binding Source={StaticResource myTodoList}}"
         ItemTemplate="{StaticResource myTaskTemplate}"/>

有关完整示例,请参阅数据模板化示例简介

注解

可以使用指定 ItemTemplate 数据对象的可视化效果。 ItemsControl如果绑定到集合对象,并且未使用 a DataTemplate提供特定显示指令,则每个项的结果 UI 是基础集合中每个对象的字符串表示形式。

设置 ItemTemplate on ItemsControl时,UI 将按如下方式生成, (使用 ListBox 示例) :

  1. 在内容生成期间,会 ItemsPanel 启动请求,以便 ItemContainerGenerator 为每个数据项创建容器。 对于 ListBox,容器是一个 ListBoxItem。 生成器调用回 ItemsControl 容器以准备容器。

  2. 准备的一部分涉及复制ItemTemplateListBoxContentTemplate成为的ListBoxItem

  3. 与所有类型的 ContentControl 类型类似, ControlTemplate 包含一个 ListBoxItem ContentPresenter。 When the template is applied, it creates a ContentPresenter whose ContentTemplate is bound to the ContentTemplate of the ListBoxItem.

  4. 最后,应用于ContentPresenterContentTemplate自身,并创建 UI。

如果定义了多个 DataTemplate 定义,并且想要提供逻辑以编程方式选择和应用 a DataTemplate,请使用该 ItemTemplateSelector 属性。

ItemsControl 视觉自定义提供了极大的灵活性,并提供许多样式和模板化属性。 ItemContainerStyle使用属性或ItemContainerStyleSelector属性设置样式以影响包含数据项的元素的外观。 例如, ListBox生成的容器是 ListBoxItem 控件;对于 ComboBox,它们是 ComboBoxItem 控件。 若要影响项的布局,请使用 ItemsPanel 该属性。 如果在控件上使用分组,则可以使用 GroupStyleGroupStyleSelector 属性。

有关详细信息,请参阅 数据模板化概述

XAML 属性用法

<object ItemTemplate=" ResourceExtension TemplateResourceKey"/>  

XAML 值

ResourceExtension
下列项之一: StaticResource 标记扩展DynamicResource 标记扩展。 除非样式本身包含对潜在运行时引用(如系统资源或用户首选项)的引用,否则通常建议使用对样式的 StaticResource 标记扩展 引用来提高性能。

TemplateResourceKey
引用作为资源请求的模板的 x:Key 指令字符串值。

依赖项属性信息

标识符字段 ItemTemplateProperty
元数据属性设置为 true

适用于

另请参阅