ItemContainerTemplate的作用是什么?它是从DataTemplate派生的,但是除了ItemContainerTemplateKey属性之外,它们之间没有任何区别。我什么时候应该使用,什么时候应该使用?
最佳答案
DataTemplate
和ItemContainerTemplate
之间的唯一区别是资源字典键的自动提供方式(假定未明确设置)。即,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}" />
两者之间的主要实际区别是,具有默认 key 的
DataTemplate
被视为隐式template2,而ItemContainerTemplate
则不是。实际上,您需要手动引用它,例如:<ListBox ItemTemplate="{StaticResource {ItemContainerTemplate {x:Type sys:String}}}" />
我不确定创建
ItemContainerTemplate
类的意图。我想它为您提供了更清晰的代码概览,您知道这样的模板专门用于ItemsControl
(或派生控件)。另外,我想编写一个可重用的DataTemplateSelector
来利用此类很简单。1从创建的对象属于不同类型的意义上说,它们不是等效的,但是在功能上它们是等效的。
2隐式模板适用于范围内相应类型的所有对象,除非显式设置了模板。
关于wpf - DataTemplate与ItemContainerTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23824607/