In the Windows form application, it is very easy to expand all the Tree nodes of a Treeview control. Microsoft has provided the expandall Method for us. We only need a simple line of code TV _qtree.expandall (); you can. That is, the Treeview. expandall method of the system. Windows. Forms namespace.
In WPF, The expandall method is unavailable in system. Windows. Controls. Treeview. The only property and method related to expansion is that each treeviewitem has an isexpanded attribute. This attribute defines whether the node is enabled. The msdn help is as follows:
Gets or sets whether the nested items in a treeviewitem are expanded or collapsed. This is a Dependency Property.
What should we do at this time? It is easy to write a recursion, traverse every subnode of the tree, and set isexpanded of each subnode to true.
You can see the solution through the following links:
Http://forums.microsoft.com/MSDN/ShowPost.aspx? Postid = 976861 & siteid = 1
Http://shevaspace.spaces.live.com/blog/cns! Fd9a0f1f8dd06954! 463. Entry
Http://blogs.msdn.com/okoboji/archive/2006/09/20/764019.aspx
We can further develop on the basis of the above solution.
Use the extension method to extend the expandall Method to the system. Windows. Controls. Treeview class. For more information about the extension method, see my previous blog: extension methods in C #3.0)
The code for my extension method is as follows:
/// <Summary>
/// Extension Method of Guo hongjun
/// </Summary>
Public static class extensionmethods
{
/// <Summary>
///
/// </Summary>
/// <Param name = "Treeview"> </param>
Public static void expandall (this system. Windows. Controls. Treeview)
{
Expandinternal (Treeview );
}
/// <Summary>
///
/// </Summary>
/// <Param name = "targetitemcontainer"> </param>
Private Static void expandinternal (system. Windows. Controls. itemscontrol targetitemcontainer)
{
If (targetitemcontainer = NULL) return;
If (targetitemcontainer. Items = NULL) return;
For (INT I = 0; I <targetitemcontainer. Items. Count; I ++)
{
System. Windows. Controls. treeviewitem treeitem = targetitemcontainer. items [I] As system. Windows. Controls. treeviewitem;
If (treeitem = NULL) continue;
If (! Treeitem. hasitems) continue;
Treeitem. isexpanded = true;
Expandinternal (treeitem );
}
}
}
For more information about how to use the extension method, see the Notes mentioned in extension methods in C #3.0.