The Tricks with TreeViewItem Expansion (Revisited)

|

Last year, I posted a blog article talking about how to expand TreeViewItems, unfortunately, the download link to the source code of that article was broken, and what's more, I lost the original source code myself, so in today's post, I want to revisit this topic with the core piece of code which actually does the trick.

using System;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace Sheva.Windows.Controls
{
    public static class TreeViewHelper
    {
        public static void ExpanAll(TreeView treeView)
        {
            ExpandSubContainers(treeView);
        }

        private static void ExpandSubContainers(ItemsControl parentContainer)
        {
            foreach (Object item in parentContainer.Items)
            {
                TreeViewItem currentContainer = parentContainer.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                if (currentContainer != null && currentContainer.Items.Count > 0)
                {
                    currentContainer.IsExpanded = true;
                    if (currentContainer.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
                    {
                        currentContainer.ItemContainerGenerator.StatusChanged += delegate
                        {
                            ExpandSubContainers(currentContainer);
                        };
                    }
                    else
                    {
                        ExpandSubContainers(currentContainer);
                    }
                }
            }
        }
    }
}

The key caveat of expanding TreeViewItems is to make sure that the container for the current TreeViewItem has been generated, so you can safely expand it to show all its sub items, that's why I make recursive call when the status of current TreeViewItem's ItemContainerGenerator is set to GeneratorStatus.ContainersGenerated.

1 comments:

Robert said...

This is just what I wanted!

I have a custom container that uses a ViewModel with checkboxes (see CodeProject.com

I added the ExpandSubContainers method, added a boolean arg to expand/contract and voila!

Thank you