How is it possible to programmatically select an item in a WPF TreeView
? The ItemsControl
model seems to prevent it.
I have created a method VisualTreeExt.GetDescendants
that returns an enumerable collection of elements that match the specified type:
public static class VisualTreeExt
{
public static IEnumerable GetDescendants(DependencyObject parent) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parent);
for (var i = 0; i < count; ++i)
{
// Obtain the child
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T)
yield return (T)child;
// Return all the descendant children
foreach (var subItem in GetDescendants(child))
yield return subItem;
}
}
}
When you ask for VisualTreeHelperExt.GetDescendants
you'll get all the TreeViewItem
childs. You can select a particular value using the following piece of code:
var treeViewItem = VisualTreeExt.GetDescendants(MyTreeView).FirstOrDefault(tvi => tvi.DataContext == newValue);
if (treeViewItem != null)
treeViewItem.IsSelected = true;
It's a bit of a dirty solution (and probably not the most efficient) and won't work if you're using a virtualized TreeView, because it depends on the existance of the actual visual elements. But it works for my situation...