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

.net, c#, treeview, wpf

Solution

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;
    }

Problem

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

Original source