WPF TreeView: Where is the ExpandAll() method

Viewed 49003

How can I expand all TreeView nodes in WPF? In WinForms there was a ExpandAll() method which does this.

8 Answers

The WPF TreeView class does not have an ExpandAll method. Thus you'd have to loop through the nodes and set their IsExpanded properties to true.

It's 2022-01-14 now, and I'm using VS2022 with .net6. I believe during 2015~now, MS built a new method named ExpandSubTree(), which can expand not the whole tree but a single TreeViewItem. It makes things easier.

CollapseAll is quite different because only the first layer need to be collapsed.

public static class TreeViewHelper
{
    public static void ExpandAll(this TreeView treeView)
    {
        foreach (var item in treeView.Items)
        {
            if (treeView.ItemContainerGenerator.ContainerFromItem(item) is TreeViewItem treeViewItem)
                treeViewItem.ExpandSubtree();
        }
    }

    public static void CollapseAll(this TreeView treeView)
    {
        foreach (var item in treeView.Items)
        {
            if (treeView.ItemContainerGenerator.ContainerFromItem(item) is TreeViewItem treeViewItem)
                treeViewItem.IsExpanded = false;
        }
    }

    public static void CollapseAll(this TreeViewItem treeViewItem)
    {
        foreach (var item in treeViewItem.Items)
        {
            if (treeViewItem.ItemContainerGenerator.ContainerFromItem(item) is TreeViewItem subTreeViewItem)
                subTreeViewItem.IsExpanded = false;
        }
    }
}
Related