Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoExpand treeview in WPF

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

like image 765
David Brunelle Avatar asked Sep 28 '09 13:09

David Brunelle


People also ask

How to expand TreeView in WPF?

To expand a treeview item you need to set the IsExpanded attribute to True. Conversely, in order to collapse an item you should set the IsExpanded attribute to False. The default value of the IsExpanded property is False.

How do you expand all Treeviews?

You can expand all nodes in the TreeView by default by setting up an ItemContainerStyle for the TreeView and specifying that you want each TreeViewItem expanded.


2 Answers

You can set ItemContainerStyle and use IsExpanded property.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">    <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

like image 172
Anvaka Avatar answered Oct 16 '22 18:10

Anvaka


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;     } } 
like image 44
Carlo Avatar answered Oct 16 '22 17:10

Carlo