How can I expand all TreeView nodes in WPF? In WinForms there was a ExpandAll() method which does this.
The answer provided by @Pierre-Olivier is a good one.
Personally, I prefer to use a stack rather than recursion in circumstances such as these where you have no idea how deeply nested the data could be. Even better, it could be provided as an extension function:
public static void ExpandAll(this TreeViewItem treeViewItem, bool isExpanded = true)
{
var stack = new Stack(treeViewItem.Items.Cast());
while(stack.Count > 0)
{
TreeViewItem item = stack.Pop();
foreach(var child in item.Items)
{
var childContainer = child as TreeViewItem;
if(childContainer == null)
{
childContainer = item.ItemContainerGenerator.ContainerFromItem(child) as TreeViewItem;
}
stack.Push(childContainer);
}
item.IsExpanded = isExpanded;
}
}
public static void CollapseAll(this TreeViewItem treeViewItem)
{
treeViewItem.ExpandAll(false);
}