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?
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 particular SomeType
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:
<Window.Resources>
<!-- Generic Button data template -->
<DataTemplate DataType="{x:Type Button}">
<!-- Elements defining the DataTemplate-->
</DataTemplate>
<!-- Generic TextBlock data template -->
<DataTemplate DataType="{x:Type TextBlock}">
<!-- Elements defining the DataTemplate-->
</DataTemplate>
<!-- Specific Button data template -->
<DataTemplate x:Key="SpecialButton" DataType="{x:Type Button}">
<!-- Elements defining the DataTemplate-->
</DataTemplate>
</Window.Resources>
This results in three entries in the resource dictionary. The orange arrows in the image, below, point to the DataTemplateKey
based entries for the Button
and TextBlock
types, while the red arrow points to the specific (keyed) entry for the SpecialButton
keyed resource:
精彩评论