wpf - DataTemplate与ItemContainerTemplate

标签 wpf xaml

ItemContainerTemplate的作用是什么?它是从DataTemplate派生的,但是除了ItemContainerTemplateKey属性之外,它们之间没有任何区别。我什么时候应该使用,什么时候应该使用?

最佳答案

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}" />

两者之间的主要实际区别是,具有默认 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/

相关文章:

设置了 Image 和 IsCheckable 的 WPF MenuItem

应用程序中的 C# WPF 多个面板 - 如何做到这一点

.net - 将行颜色绑定(bind)到 MVVM 中的属性(取决于行中的数据)

c# - 使用 MVVM 在 MainWindow 上绑定(bind) UserControl View 模型

c# - 使用 WPF 时的数据绑定(bind)问题

c# - 当我尝试将元素添加到 Xamarin.Forms 应用程序中的 ObservableCollection 时出现 InvalidCastException

wpf - 使用 Xaml Styler 的经验?

C# Winforms-WPF 互操作

c# - Xamarin Forms 找不到如何将对象与详细信息 View 绑定(bind)

c# - 使用代码隐藏堆叠列系列在 WPF 图表上旋转独立轴标签