How does WPF expand all Treeview Tree nodes?

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.