Sometimes you might have to specify a HierarchicalDataTemplate for a templated type. If so, you can only do this in code-behind. (If you have to do this in XAML try wrapping that template type within a non-templated dummy type.)
For example, if you have to do something like this:
<HierarchicalDataTemplate ItemsSource='{Binding}'
DataType='{x:Type local:MyTemplatedList<int>}'>
<TextBlock Text='{Binding Name}'></TextBlock>
</HierarchicalDataTemplate>
The above wouldn’t compile because the XAML compiler doesn’t support this.
So, you will have to do this in code-behind instead:
using MyListType = MyTemplatedList;
// Then in Window’s constructor for example:
HierarchicalDataTemplate hdt = new HierarchicalDataTemplate(typeof(MyListType));
hdt.ItemsSource = new Binding();
FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
tb.SetBinding(TextBlock.TextProperty, new Binding('Name'));
hdt.VisualTree = tb;
this.Resources[new DataTemplateKey(typeof(CountryList))] = hdt;
Note that the above code also illustrates how to add a HierarchicalDataTemplate resource to the Resources list without specifying a key.
Share with