There is a DataTemplateSelector :

 class DisplayTemplateSelector : DataTemplateSelector { public DataTemplate TemplateA { get; set; } public DataTemplate TemplateB { get; set; } public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container) { var baseClass = item as BaseClass; switch (baseClass.Type) { case A: return TemplateA; case B: return TemplateB; default: return null; } } } 

XAML

 <HierarchicalDataTemplate x:Key="key" ItemsSource="{Binding Streams, Mode=OneWay}" ItemTemplateSelector="{StaticResource displayTemplateSelector}"> <TextBlock Text="{Binding Name}"/> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type A}" x:Key="a"> <TextBlock Text="{Binding }"/> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type B}" x:Key="b"> <TextBlock Text="{Binding }"/> </HierarchicalDataTemplate> 

At this stage, everything works. But as soon as I want to set the ItemSource and ItemTemplate for one of the A or B templates, I get an exception:

Duplex assembly requires Path or XPath.

and a warning in the output:

Both 'ItemTemplate' and 'ItemTemplateSelector' are set; 'ItemTemplateSelector' will be ignored. TreeViewItem:'TreeViewItem' (Name='')

What is the problem?


UDP:

The problem was due to the binding in templates A, B.

 <TextBlock Text="{Binding }"/> 

it was necessary to be attached to a specific field.

  • If you want Mode = TwoWay, then you need to set the Path in the Binding. If not, then you need to set Mode = OneWay. Concerning the warning, you must either remove the TextBlock or DataTemplateSelector. - Vlad
  • @Vlad, so it’s worth OneWay, but I tried it in different ways. Selector to remove? I can't do without him) - Gardes
  • Then remove the template. There must be one thing. You either choose or use what you set in the markup. Where is it? I'm not talking about ItemSource, I'm talking about TextBlock. - Vlad
  • @Vlad, HierarchicalDataTemplate allows you to set a template for yourself and for the sub-items through the ItemTemplate. so I'm afraid that's not the point - Gardes
  • Do you have the opportunity to write MCVE? - user227049

0