Get a TreeViewItem’s Parent item
Further to Gerrod’s post on selecting an item in a treeview, I found myself scratching my head on how to find a treeviewitem’s parent item. Here I was expecting a TreeViewItem.Parent property. Unfortunately after scouring the dark depths of the internet, I found that using the VisualTreeHelper class was the answer:
private static TreeViewItem GetParentTreeViewItem(DependencyObject item)
{
if (item != null)
{
DependencyObject parent = VisualTreeHelper.GetParent(item);
TreeViewItem parentTreeViewItem = parent as TreeViewItem;
return parentTreeViewItem ?? GetParentTreeViewItem(parent);
}
return null;
}
I’m sure this can be easily converted into an extension method for those of you expecting the Parent property like I was.
You have to be careful whenever using this though. In WPF there are logical and visual trees and they are often very different beasts. this.Parent will actually traverse the logical tree, so say for example with a button in a Listbox item, the button.parent will return the listbox, however visualtreehelper is going to traverse the visual tree, which means that using VisualTreeHelper.GetParent will vary depending on what template/resources you are using. There are reasons for the two different methods so make sure you know the ins and outs of what you are expecting to traverse when using it, it isnt really a replacement for the frameworkelement.Parent method.