Search code examples
wpftreeviewhierarchicaldatatemplate

How to get TreeViewItem from HierarchicalDataTemplate item?


I have a TreeView which uses a HierarchicalDataTemplate to bind its data.

It looks like this:

<TreeView x:Name="mainTreeList" ItemsSource="{Binding MyCollection}>
  <TreeView.Resources>
    <HierarchicalDataTemplate 
     DataType="{x:Type local:MyTreeViewItemViewModel}" 
     ItemsSource="{Binding Children}">
      <!-- code code code -->
    </HierarchicalDataTemplate>
  </TreeView.Resources>
</TreeView>

Now, from the code-behind of say the main window, I want to get the current selected TreeViewItem. However, if I use:

this.mainTreeList.SelectedItem;

The selectedItem is of type MyTreeViewItemViewModel. But I want to get the 'parent' or 'bound' TreeViewItem. I do not pass that to my TreeViewItemModel object (wouldn't even know how).

How can I do this?


Solution

  • From Bea Stollnitz's blog entry about this, try

    TreeViewItem item = (TreeViewItem)(mainTreeList
        .ItemContainerGenerator
        .ContainerFromIndex(mainTreeList.Items.CurrentPosition));