I have a 4-level tree structure, defined by:
<HierarchicalDataTemplate DataType='{x:Type src:Level1}' ItemsSource='{Binding Path=Level2Items}'> <TextBlock Text='{Binding Path=Level1Name}'/> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType='{x:Type src:Level2}' ItemsSource='{Binding Path=Level3Items}'> <TextBlock Text='{Binding Path=Level2Name}'/> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType='{x:Type src:Level3}' ItemsSource='{Binding Path=Level4Items}'> <TextBlock Text='{Binding Path=Level3Name}'/> </HierarchicalDataTemplate> <DataTemplate DataType='{x:Type src:Level4}'> <TextBlock Text='{Binding Path=Level4Name}'/> </DataTemplate>
And it works great. The only thing is, I can’t programmatically select any of my bound items, because they’re not of type TreeViewItem (and therefore don’t have the ‘IsSelected’ property). Is there a way to automatically wrap databound items in a particular container type (in this case: TreeViewItem)?
If your items are in a
TreeView, they’ll be wrapped in aTreeViewItemautomatically by theTreeView‘sItemContainerGenerator. You can do something like this to ensure theIsSelectedproperty onTreeViewItemmaps to a property on your data class: