How to get all the elements of a WPF TreeView as a

2019-05-22 13:21发布

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?

Thanks

2条回答
祖国的老花朵
2楼-- · 2019-05-22 13:52

Here is what you asked;

private static TreeViewItem[] getTreeViewItems(TreeView treeView)
{
    List<TreeViewItem> returnItems = new List<TreeViewItem>();
    for (int x = 0; x < treeView.Items.Count; x++)
    {
        returnItems.AddRange(getTreeViewItems((TreeViewItem)treeView.Items[x]));
    }
    return returnItems.ToArray();
}
private static TreeViewItem[] getTreeViewItems(TreeViewItem currentTreeViewItem)
{
    List<TreeViewItem> returnItems = new List<TreeViewItem>();
    returnItems.Add(currentTreeViewItem);
    for (int x = 0; x < currentTreeViewItem.Items.Count; x++)
    {
        returnItems.AddRange(getTreeViewItems((TreeViewItem)currentTreeViewItem.Items[x]));
    }
    return returnItems.ToArray();
}

Call with your control as the first parameter e.g.;

getTreeViewItems(treeView1);
查看更多
Animai°情兽
3楼-- · 2019-05-22 13:53

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.

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;
    }
查看更多
登录 后发表回答