WPF TreeView ItemTemplateSelector not working

1.6k Views Asked by At

I have a TreeView and two HierachicalDataTemplates: one with DataType="{x:Type local:Department}" x:Key="D" and one with DataType="{x:Type local:Employee}" x:Key="E"

if I leave out the x:keys it works (because Templates are picked up automatically), but if I use an ItemTemplateSelector, I can step into the selector and see that the correct HierarchicalDataTemplate is being returned but that the contents don't show up.

XAML:

<Window.Resources>
  <local:MyItemSelector x:Key="sel"/>
</Window.Resources>

<TreeView ItemsSource={Binding Data}" ItemTemplateSelector="{StaticResource sel}"/>

C#:

class MyItemSelector : DataTemplateSelector {
  public override DataTemplate SelectTemplate(object item, DependencyObject container) {
    var cntrl = container as Control;
    if (cntrl == null) return null;

    if (item is Department)
      return cntrl.FindResource("D") as HierarchicalDataTemplate;
    if (item is Employee)
      return cntrl.FindResource("E") as HierarchicalDataTemplate;

    return null;
  }
}

any ideas?

0

There are 0 best solutions below