How can I expand all TreeView nodes in WPF? In WinForms there was a ExpandAll() method which does this.
In addition to user2779123's comment and I know this is long since been answered but I would also suggest that Pierre-Olivier Pignon's code push the treeItem.IsExpanded = true; not only be moved into scope of the null check but by moving it to the ExpandAll procedure as it appears to be written in a format that allows for both expansion and collapsing of the tree structure and moving this to there would add the root nodes to this functionality by design.
As per the below example:
private void ExpandAll(ItemsControl items, bool expand)
{
items.IsExpanded = expand;
foreach (object obj in items.Items)
{
ItemsControl childControl = items.ItemContainerGenerator.ContainerFromItem(obj) as ItemsControl;
if (childControl != null)
{
ExpandAll(childControl, expand);
}
TreeViewItem item = childControl as TreeViewItem;
if (item != null)
item.IsExpanded = true;
}
}
private void btnExpandAll_Click(object sender, RoutedEventArgs e)
{
foreach (object item in this.myTV.Items)
{
TreeViewItem treeItem = this.myTV.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
if (treeItem != null)
ExpandAll(treeItem, true);
}
}