wpftreeviewhierarchytreeviewitem

TreeViewItem.ParentTreeViewItem is internal but is there a way to get it?


I'm trying to write code that can accept Key.Down and Key.Up and change the selection of a TreeView that is using several HierarchicalDataTemplates. In the children of a TreeViewItem, I need to get its parent so that I can determine what the next node should be selected. I noticed that TreeViewItem has a ParentTreeViewItem property, but its set to internal and therefore not exposed to access. Is there another way to emulate how to get the parent of a TreeViewItem as a TreeViewItem? Note: Parent is always null when using HierarchicalDataTemplate. Thanks in advance.

enter image description here


Solution

  • You can always use the VisualTreeHelper.GetParent to find any parent element:

    private bool TryGetVisualParent<TParent>(DependencyObject element, out TParent parent) where TParent : DependencyObject
    {
      parent = null;
    
      if (element is null)
      {
        return false;
      }
    
      element = VisualTreeHelper.GetParent(element);
      if (element is TParent parentElement)
      {
        parent = parentElement;
        return true;
      }
    
      return TryGetVisualParent(element, out parent);
    }
    

    Usage Example

    private void OnTreeViewItem_Selcted(object sender, RoutedEventArgs e)
    {
      var selectedItem = e.OriginalSource as TreeViewItem;
      if (TryGetVisualParent(selectedItem, out TreeViewItem parentItem))
      {
        // Handle 'parentItem'
      }
    }