WPF - 在没有键的情况下在 ResourceDictionary 中定义 DataTemplate
我已经多次看到这种形式的 wpf 代码示例:
<Window.Resources>
<DataTemplate DataType="{x:Type SomeType}">
<!-- Elements defining the DataTemplate-->
</DataTemplate>
</Window.Resources>
我理解用法,但我无法理解为什么这种语法可以:由于 ResourceDictionary 实现了 IDictionary,因此我们添加到 Resource 属性的每个元素都必须指定一个键。现在我知道使用 DictionaryKeyPropertyAttribute,类可以提供隐式键值 - 但对于 DataTemplate 类,提供的属性是“DataTemplateKey”。我知道这听起来有点小,但这个问题的动机是知道如何使用其他类,即使我之前没有权限查看使用示例(也许是一些第三方......)。有人吗?
I have seen many times wpf code samples in this form:
<Window.Resources>
<DataTemplate DataType="{x:Type SomeType}">
<!-- Elements defining the DataTemplate-->
</DataTemplate>
</Window.Resources>
I understand the usage, but I cant understand why is this syntax is ok: since ResourceDictionary implements IDictionary, therefore every element that we add to Resource property must specify a key. Now I know that using the DictionaryKeyPropertyAttribute, a class can provide an implicit key value - but in case of DataTemplate class, the provided property is "DataTemplateKey". I know it sounds a bit petty, but the motivation for this question is to know how to use other classes even if I didnt have the privilege to see usage samples before (maybe some 3rd party...). anyone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您在问题中提到的,没有
x:Key
属性的条目使用 DataTemplateKey(SomeType) 作为键。您只能为资源中的特定SomeType
指定一个此类实例。 DataTemplateKey 派生自 TemplateKey ,而它本身又派生自ResourceKey。当然,这样的 DataTemplate 资源定义可以出现在许多类型中,并保持唯一,因为每个相应类型的 DataTemplateKey 都是唯一的。例如,考虑以下资源定义:
这会在资源字典中产生三个条目。下图中的橙色箭头指向
Button
和TextBlock
类型的基于DataTemplateKey
的条目,而红色箭头则指向SpecialButton
键控资源的特定(键控)条目:As you mentioned in your question, entries without an
x:Key
attribute use DataTemplateKey(SomeType) as the key. You can only specify one such instance for a particularSomeType
in the resources. DataTemplateKey is derived from TemplateKey which itself is derived from ResourceKey. Of course such DataTemplate resource definitions can appear for many types, staying unique, because the DataTemplateKey of each respective type will be unique.For example, consider the following Resources definition:
This results in three entries in the resource dictionary. The orange arrows in the image, below, point to the
DataTemplateKey
based entries for theButton
andTextBlock
types, while the red arrow points to the specific (keyed) entry for theSpecialButton
keyed resource: