如何获得一个WPF树视图的所有作为一个列表中的元素?作为一个、视图、如何获得、元素

2023-09-04 04:00:24 作者:聽說妳心裏有鬼

我需要访问一个TreeView的节点作为一个普通列表(好像所有的地方展开的节点)能够做到多选pressing Shift键。有没有办法做到这一点?

I need to access the nodes of a TreeView as a plain list (as if all the nodes where expanded) to be able to do multiselection pressing the Shift key. Is there a way to accomplish this?

感谢

推荐答案

下面是一个会检索一个TreeView所有TreeViewItems方法。请注意,这是一个非常昂贵的方法来运行,因为它必须展开所有TreeViewItems节点和执行UpdateLayout请各一次。由于TreeViewItems正在扩大父节点时才会建立,有没有其他的方法来做到这一点。

Here is a method that will retrieve all the TreeViewItems in a TreeView. Please be aware that this is an extremely expensive method to run, as it will have to expand all TreeViewItems nodes and perform an updateLayout each time. As the TreeViewItems are only created when expanding the parent node, there is no other way to do that.

如果你只需要一个已经打开的节点列表,你可以删除code表示展开它们,它就会便宜很多。

If you only need the list of the nodes that are already opened, you can remove the code that expand them, it will then be much cheaper.

也许你应该尝试寻找另一种方式来管理多选。话虽如此,这里是方法:

Maybe you should try to find another way to manage multiselection. Having said that, here is the method :

    public static List<TreeViewItem> FindTreeViewItems(this Visual @this)
    {
        if (@this == null)
            return null;

        var result = new List<TreeViewItem>();

        var frameworkElement = @this as FrameworkElement;
        if (frameworkElement != null)
        {
            frameworkElement.ApplyTemplate();
        }

        Visual child = null;
        for (int i = 0, count = VisualTreeHelper.GetChildrenCount(@this); i < count; i++)
        {
            child = VisualTreeHelper.GetChild(@this, i) as Visual;

            var treeViewItem = child as TreeViewItem;
            if (treeViewItem != null)
            {
                result.Add(treeViewItem);
                if (!treeViewItem.IsExpanded)
                {
                    treeViewItem.IsExpanded = true;
                    treeViewItem.UpdateLayout();
                }
            }
            foreach (var childTreeViewItem in FindTreeViewItems(child))
            {
                result.Add(childTreeViewItem);
            }
        }
        return result;
    }