Generally, the treeviewitem in the Treeview can be generated in two ways:
1. directly use the treeviewitem label in XAML (use C # code to do the same, in short, explicitly use treeviewitem)
2. Data Binding, such as binding to XML or arrays.
Solution to the first situation:
Add the expandall () method to the Treeview.
Public static class extensionmethods
{
Public static void expandall (this system. Windows. Controls. Treeview)
{
Expandallitems (Treeview );
}
Private Static void expandallitems (itemscontrol Control)
{
If (control = NULL)
{
Return;
}
Foreach (Object item in control. Items)
{
System. Windows. Controls. treeviewitem treeitem = control. itemcontainergenerator. containerfromitem (item) as treeviewitem;
If (treeitem = NULL |! Treeitem. hasitems)
{
Continue;
}
Treeitem. isexpanded = true;
Expandallitems (treeitem as itemscontrol );
}
}
}
Pay attention to the Red Line. This can be used when the item is not treeviewitem.
Then add the following method in the window. contentrendered event processing method:
Void mainwindow_contentrendered (Object sender, eventargs E)
{
This. Treeview. expandall ();
}
Solution to the second situation:
First, combine the methods in the first case, and then add the following code in the XAML code:
<Window. Resources>
<Style targettype = "treeviewitem">
<Setter property = "isexpanded"
Value = "{binding isexpanded,
Mode = oneway,
Relativesource = {relativesource findancestor, ancestortype = {X: Type treeviewitem }}"/>
</Style>
</Window. Resources>
This will solve the problem caused by data binding:
1. Items in Treeview is not treeviewitem
2. itemcontainergenerator. containerfromitem (item) can only be used at the first level of the Treeview itself. For deeper calls, itemcontainergenerator. _ status is notstarted.