DataTemplate与ItemContainerTemplate

时间:2014-05-23 08:40:11

标签: wpf xaml

ItemContainerTemplate用于什么?它源自DataTemplate,但除了ItemContainerTemplateKey属性之外,我没有看到它们之间的任何差异。我什么时候应该使用一个而另一个?

5 个答案:

答案 0 :(得分:4)

DataTemplateItemContainerTemplate之间的唯一区别是自动提供资源字典键的方式(假设未明确设置)。即,DataTemplate饰有[DictionaryKeyProperty("DataTemplateKey")]属性,DataTemplateKey基本上定义为:

public object DataTemplateKey
{
    get { return (DataType != null) ? new DataTemplateKey(DataType) : null; 
}

请参阅DataTemplate source以供参考。

ItemContainerTemplate派生自DataTemplate,但使用[DictionaryKeyProperty("ItemContainerTemplateKey")]属性修饰(实际上替换了继承的属性),ItemContainerTemplateKey属性定义如下:

public object ItemContainerTemplateKey
{
    get { return (DataType != null) ? new ItemContainerTemplateKey(DataType) : null; }
}

请参阅ItemContainerTemplate source以供参考。

差异似乎很小 - DataTemplate返回DataTemplateKey的实例,ItemContainerTemplate返回ItemContainerTemplateKey的实例(均来自TemplateKey)。所以基本上这两个是等价的 1

<ItemContainerTemplate DataType="{x:Type sys:String}" />
<DataTemplate x:Key="{ItemContainerTemplateKey {x:Type sys:String}}" />

以及这些:

<ItemContainerTemplate x:Key="{DataTemplateKey {x:Type sys:String}}" />
<DataTemplate DataType="{x:Type sys:String}" />

这两者之间的主要实际差异是,DataTemplate默认密钥被视为隐式模板 2 ,而ItemContainerTemplate则不是。实际上,您需要手动引用它,例如:

<ListBox ItemTemplate="{StaticResource {ItemContainerTemplate {x:Type sys:String}}}" />

我不确定创建ItemContainerTemplate课程的意图。我想它可以让您更清楚地了解代码,您知道这样的模板专门用于ItemsControl(或派生控件)。另外,我想编写一个强大的可重用DataTemplateSelector可以很好地利用这个类。

1 在创建的对象属于不同类型的意义上,它们并不相同,但在功能上它们是等效的。

2 除非明确设置模板,否则隐式模板将应用于范围内相应类型的所有对象。

答案 1 :(得分:2)

ItemContainerTemplate描述了您的Item周围的世界。例如,在ListBox中,ListBoxItem周围的选择矩形。 DataTemplate描述了ListBoxItem如何以及它包含的元素。

博士。 WPF做了一个很好的例子: http://drwpf.com/blog/category/item-containers/

答案 2 :(得分:1)

您可以在ItemContainerTemplate中加ResourceDictionary,它会自动使用DataType作为密钥。

那是only difference

答案 3 :(得分:0)

ItemContainerTemplate 在您需要为 ItemsControl 使用不同的 Item 容器时很有用/必要。 通常 XAML 基础结构决定用于给定 ItemsControl 的项目容器:

  • ListBox 使用 ListBoxItem
  • DataGrid 使用 DataRow
  • ComboBox 使用 ComboBoxItem
  • Menu 使用 MenuItem

至于菜单,您有时需要一个分隔符(从技术上讲,这不是 MenuItem) 这就是 ItemContainerTemplate、ItemContainerTemplateSelector 和 ItemContainerTemplatekey 发挥作用的地方。 根据视图模型/数据上下文类型或其一个/多个属性值,您可以在 ItemContainerTemplate 中的 Separator 和另一个中的 MenuItem 之间切换 项目容器模板。 您可以使用触发器或 ItemContainerTemplateSelector 来实现这一点。
实际上,老实说,我自己刚刚要了解 ItemContainerTemplateKey 的用途。 我想我已经明白,这是一种将 ItemContainerTemplate 映射到数据类型的简单方法,无需选择器或隐藏代码或触发器。

如果您对默认的 ItemContainerTemplate 没问题,则根本不需要在 XAML 中处理它。可以在 ItemContainerTemplate 中实现对 ItemsContainer 样式的操作。在 ItemTemplate 中使用自定义 DataTemplate 来绑定您的数据(以及对其进行样式设置)。 很少需要使用 ItemContainerTemplate。但有时很方便。

答案 4 :(得分:-1)

您可以检查该链接以查看controltemplate和datatemplate与hierarchicaldatatemplate itemspaneltemplate之间的区别:

http://nirajrules.wordpress.com/2009/03/08/controltemplate-vs-datatemplate-vs-hierarchicaldatatemplate-vs-itemspaneltemplate/