tags:

views:

265

answers:

2

Is there a way to automatically expand all nodes from a treeview in WPF? I searched and didn't even find an expand function in the treeview property.

Thanks

A: 

This is what I use:

 private void ExpandAllNodes(TreeViewItem rootItem)
 {
  foreach (object item in rootItem.Items)
  {
   TreeViewItem treeItem = (TreeViewItem)item;

   if (treeItem != null)
   {
    ExpandAllNodes(treeItem);
    treeItem.IsExpanded = true;
   }
  }
 }

In order for it to work you must call this method in a foreach loop for the root node:

// this loop expands all nodes
foreach (object item in myTreeView.Items)
{
 TreeViewItem treeItem = (TreeViewItem)item;

 if (treeItem != null)
 {
  ExpandAllNodes(treeItem);
  treeItem.IsExpanded = true;
 }
}
Carlo
Hi Carlo. This will not work if you have something different from TreeViewItem in your Items collection. If you want to be sure this approach works in any case, you should use ItemContainerGenerator from your TreeView object and call it's ContainerFromItem() method.
Anvaka
You are right, the way I add the items to my treeview is myTree.Items.Add(new TreeViewItem() { Header = myObject });, That's why it works for me. Sorry for misleading.
Carlo
+1  A: 

Hi David,

You can set ItemContainerStyle and use IsExpended property.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
   <Grid>
      <TreeView>
         <TreeView.ItemContainerStyle>
            <Style TargetType="{x:Type TreeViewItem}">
               <Setter Property="IsExpanded" Value="True"/>
            </Style>
         </TreeView.ItemContainerStyle>
         <TreeViewItem Header="Header 1">
            <TreeViewItem Header="Sub Item 1"/>
         </TreeViewItem>
         <TreeViewItem Header="Header 2">
            <TreeViewItem Header="Sub Item 2"/>
         </TreeViewItem>
      </TreeView>
   </Grid>
</Page>

If you need to do this from code, you can write viewmodel for your tree view items, and bind IsExpanded property to corresponding one from model. For more examples refer to great article from Josh Smith on CodeProject: Simplifying the WPF TreeView by Using the ViewModel Pattern

Anvaka