【发布时间】:2021-06-09 05:10:29
【问题描述】:
ItemContainerTemplate 是做什么用的?它派生自 DataTemplate,但除了 ItemContainerTemplateKey 属性外,我看不出它们之间有任何区别。我应该什么时候使用一个,什么时候使用另一个?
【问题讨论】:
ItemContainerTemplate 是做什么用的?它派生自 DataTemplate,但除了 ItemContainerTemplateKey 属性外,我看不出它们之间有任何区别。我应该什么时候使用一个,什么时候使用另一个?
【问题讨论】:
DataTemplate 和ItemContainerTemplate 之间的唯一区别是自动提供资源字典键的方式(假设未显式设置)。即DataTemplate被[DictionaryKeyProperty("DataTemplateKey")]属性修饰,DataTemplateKey基本定义为:
public object DataTemplateKey
{
get { return (DataType != null) ? new DataTemplateKey(DataType) : null;
}
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在创建的对象属于不同类型的意义上,它们并不等效,但在功能上它们是等效的。 p>
2隐式模板应用于范围内相应类型的所有对象,除非显式设置模板。
【讨论】:
ItemContainerTemplate 描述了您的项目周围的世界。例如,在 ListBox 中,您的 ListBoxItem 周围的选择矩形。 DataTemplate 描述了 ListBoxItem 如何出现以及它包含哪些元素。
博士。 WPF 做了一个很好的例子: http://drwpf.com/blog/category/item-containers/
【讨论】:
ItemContainerTemplate 类误认为ItemsControl.ItemContainerStyle 属性...
您可以将ItemContainerTemplate 放在ResourceDictionary 中,它会自动使用DataType 作为其键。
【讨论】:
new ItemContainerTemplateKey(DataType)作为key。
当您需要为 ItemsControl 提供不同的项目容器时,ItemContainerTemplate 很有用/必要。 通常 XAML 基础结构决定哪个项目容器用于给定的 ItemsControl:
至于菜单,您有时会需要分隔符(从技术上讲,它不是 MenuItem)
这就是 ItemContainerTemplate、ItemContainerTemplateSelector 和 ItemContainerTemplatekey 发挥作用的地方。
根据 viewmodel/datacontext 类型或其一个/多个属性值,您可以在 ItemContainerTemplate 中的 Separator 和另一个中的 MenuItem 之间切换
项目容器模板。
您可以使用触发器或 ItemContainerTemplateSelector 来实现此目的。
实际上,老实说,我自己现在才刚刚了解 ItemContainerTemplateKey 的用途。
我认为已经理解这是一种将 ItemContainerTemplate 映射到数据类型的简单方法,无需选择器或代码或触发器。
如果您对默认的 ItemContainerTemplate 没问题,您根本不需要在 XAML 中处理它。可以在 ItemContainerTemplate 中操作 ItemsContainer 样式。在 ItemTemplate 中使用自定义 DataTemplate 来绑定您的数据(以及对其进行样式设置)。 很少需要使用 ItemContainerTemplate。但有时非常方便。
【讨论】:
您可以检查该链接以查看 controltemplate 和 datatemplate 以及 hierarchydatatemplate itemspaneltemplate 之间的区别:
【讨论】: