How to programmatically select an item in a WPF TreeView?

后端 未结 16 2300
时光取名叫无心
时光取名叫无心 2020-11-28 08:42

How is it possible to programmatically select an item in a WPF TreeView? The ItemsControl model seems to prevent it.

16条回答
  •  失恋的感觉
    2020-11-28 08:52

    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(MyAmazingTreeView) 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...

提交回复
热议问题