My tree view seems like this
if I got you correctly you want to retrieve the TreeViewItem
from the SelectedItem
so you can make use of ItemContainerGenerator
ItemContainerGenerator gen = ArticlesTreeView.ItemContainerGenerator;
TreeViewItem item = gen.ContainerFromItem(ArticlesTreeView.SelectedItem) as TreeViewItem;
Get TreeViewItem from nested items
due to the reason that every TreeViewItem
has it's own ItemContainerGenerator
so in order to find the container from the nested items we need to recurse the depth of the tree
private void ArticlesTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
var item = ContainerFromItem(ArticlesTreeView.ItemContainerGenerator, ArticlesTreeView.SelectedItem);
}
private static TreeViewItem ContainerFromItem(ItemContainerGenerator containerGenerator, object item)
{
TreeViewItem container = (TreeViewItem)containerGenerator.ContainerFromItem(item);
if (container != null)
return container;
foreach (object childItem in containerGenerator.Items)
{
TreeViewItem parent = containerGenerator.ContainerFromItem(childItem) as TreeViewItem;
if (parent == null)
continue;
container = parent.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
if (container != null)
return container;
container = ContainerFromItem(parent.ItemContainerGenerator, item);
if (container != null)
return container;
}
return null;
}