C # WPF Parent control finds child controls by using the visual tree

Source: Internet
Author: User

When we design the foreground interface using WPF, we often rewrite the data template or put the control in the data template. But once the control is placed in the data template, there is no way to get it through the name of the control in the background, and there is no way to manipulate it (for example, to hide, to change a value of the control).

If you are whiter than I am, and not clear about what I have just stated, then I will briefly say what is to put the control in the data template, what kind of situation can not be in the background by name to get the control, if the reader for the data template these things are clear, or only care about how to use the visual tree to skip this part.

First, the code describes what a data template takes as an example of a ListBox control in WPF:

<listbox name= "listbox_1" horizontalalignment= "left" height= "299" margin= "10,10,0,0" verticalalignment= "Top" Width= "497" mousedoubleclick= "Listbox_1_onmousedoubleclick" >
<ListBox.ItemTemplate>
<DataTemplate>
<button name= "button_1" content= "666" ></Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

I set up 8 rows of item in the background, the effect is as follows:

We can see that the effect of overriding the data template implementation is that each item in the ListBox is a button, and here are just a few examples of simple applications that rewrite the template to be very powerful. Because if the use of the visual tree is mostly because using the data template in the background with the name can not find the corresponding control, so this brief introduction, easy to understand.

Next we try to find our ListBox and button in the background by the name of the control

We found that the listbox could be found through the name of the control, but the button could not be found by the button's name, which is the ghost of the data template.

But it doesn't matter, we can find its child control from the listbox through the visual tree the button we want.

The point is, first on the code, the visual tree finds its child controls through the parent control:

 list<t> findvisualchild<t> (DependencyObject obj) where  t:dependencyobject {try                 {list<t> List = new List<t>  (); for (int i = 0; i < visualtreehelper.getchildrencount (obj); i++ ) {DEPENDENCYOB                    ject Child =  Visualtreehelper.getchild (obj, i); if (Child is  T) {list. ADD ((T) child); list<t> Childofchildren = findvisualchild<t>  (child); if (Childofchildren! = null ) {list. AddRange (Childofchildren); }} else  {list<t> Childofchildren = Findvisualchild<t>  (child); if (Childofchildren! = null  ) {list. AddRange (Childofchildren); }}} return  list;} catch  (Exception) {//messagebox.show (EE. Message); return null ;}}               

First copy the above method into your project, and the application for the visual tree is half done.

Next the code, through the visual tree double-click the Ltem of the listbox to change the content value of the corresponding button from 666 to 777:

private void Listbox_1_onmousedoubleclick (object sender, MouseButtonEventArgs e)        {            ListBoxItem Mylistboxitem = (ListBoxItem) ListBox_1.ItemContainerGenerator.ContainerFromItem (listbox_1.selecteditem);            list<button> btnlist = findvisualchild<button>(mylistboxitem);            foreach (var item in btnlist)            {                item. Content = "777";            }        }    

The effect is to double-click on which item which item has the button changed from 666 to 777.

We found the child control button inside the parent control, and we can do anything about it (and find it by name).

The above code on the visual tree can be applied to the Listbox,datagrid,listview,treeview, for ". Itemcontainergenerator.containerfromitem "The meaning of this code I do not understand for the time being, welcome to teach and exchange.

From the above example, I believe that the reader can already use the visual tree to find the appropriate control, but in my development process has encountered some problems, and for the use of a visual tree a little bit of advice.

1. If you are using the visual tree to perform "ListBoxItem Mylistboxitem = (listboxitem) ListBox_1.ItemContainerGenerator.ContainerFromItem ( Listbox_1.selecteditem); " The return value is empty (actually not empty), probably because the interface is not initialized, I understand that the control has not been generated in the foreground, or you modified the value but the foreground has not been modified, you can add this sentence:

The name of the control. UpdateLayout ();

After the use of the visual tree, this article of the statement and description may be a little less rigorous, welcome to communicate.

2. The visual tree uses recursive methods, so its efficiency is not very high, if you use a large number of visual tree in the program, will make the program slower.

3. Call the list returned by the visual tree if the corresponding control or exception is not found, it is recommended that when you traverse the list returned by the visual tree, you should first determine whether it is null or not.

The above content is welcome to communicate, or small white.

2018.8.15 5:30 P.M. more than two minutes

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.