WPF - defining a DataTemplate inside a ResourceDictionary without a key

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 use, but I can’t understand why this syntax is fine: since the ResourceDictionary implements IDictionary, therefore, each element that we add to the Resource property must indicate a key. Now I know that with DictionaryKeyPropertyAttribute the class can provide an implicit key value, but in the case of the DataTemplate class, the property provided is "DataTemplateKey". I know this sounds a bit petty, but the motivation for this question is to know how to use other classes, even if I did not have the privilege to see usage patterns before (maybe some third-party ...). is anyone

+4
source share
1 answer

As you mentioned in your question, records without the x:Key attribute use the DataTemplateKey (SomeType) as the key. You can specify only one such instance for a specific SomeType in resources. The DataTemplateKey is derived from the TemplateKey , which itself is derived from the ResourceKey . Of course, such DataTemplate resource definitions can be displayed for many types, remaining unique, since the DataTemplateKey of each corresponding type will be unique.

For example, consider the following Resource 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> 

The result is three entries in the resource dictionary. The orange arrows in the image below indicate DataTemplateKey entries for the Button and TextBlock types, while the red arrow indicates a specific record (key) for the SpecialButton resource:

enter image description here

+3
source

Source: https://habr.com/ru/post/1341545/


All Articles