Tutorial :Can I automatically wrap HierarchicalDataTemplate items inside of a TreeViewItem?



Question:

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)?


Solution:1

If your items are in a TreeView, they'll be wrapped in a TreeViewItem automatically by the TreeView's ItemContainerGenerator. You can do something like this to ensure the IsSelected property on TreeViewItem maps to a property on your data class:

<TreeView>      <TreeView.ItemContainerStyle>          <Style TargetType="TreeViewItem">              <Setter Property="IsSelected" Value="{Binding MyIsSelectedProperty}"/>          </Style>      </TreeView.ItemContainerStyle>  </TreeView>  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »