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

Time:03-24

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

CodePudding user response:

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'
  }
}

CodePudding user response:

Use TreeViewItem.Parent Property,If the parent property is null, it means there is no parent node

 <TreeView>
      <TreeViewItem Header="root">
            <TreeViewItem Header="child" Name="child_item"></TreeViewItem>
      </TreeViewItem>
 </TreeView>

enter image description here

enter image description here

  • Related