How to find child elements in a data template in WPF

Source: Internet
Author: User
Tags resource

Two days ago when writing a WPF program, I suddenly found that the DataGrid control did not have a filter, but I was not in a hurry because I knew that the advantage of WPF was the separation of the UI from the logic, and that it was not complicated to add input filtering to the data grid controls, or to find the sixth party Derive a class directly from the DataGrid class, and redefine its control template, and add a StackPanel to the original control template on the DataGrid, with a horizontal alignment and below the column header. Then you can enter the filter information by adding N text boxes to that StackPanel in the code based on the individual columns. Oh, although not perfect, to solve the urgent problem is still possible.

So I think of another question, how to modify the elements inside the DataTemplate. Or how to get the specified element.

So, I have two programs in mind:

1, when the definition of datatemplate, such as I used a TextBlock control, I named it tbtext, and then I will iterate over the collection control of the items, and get the ContentTemplate object of each item container, Hope to use the FindName method to directly remove the TextBlock, but an exception, this method is not. Note that if DataTemplate is defined in a resource, you cannot directly modify the contents of the resource, because this change causes all items to change because each item in the collection control (such as a ListBox) refers to the same resource. And what I want now is that the foreground color of the TextBlock in each item is different.

2, I think of the VisualTreeHelper class, right, directly from the item container (ListBoxItem) level to start, a layer down to find, until found TextBlock, because my template only a TextBlock, I don't have to call it what name, As long as the TextBlock type is OK. But because there are more layers of elements, it is impossible to find TextBlock in the first round, so I wrote a recursive method, the element of all the child elements have been doubled.

Modified  
private void Findchildbytype (DependencyObject relate, type type, ref FrameworkElement Reselement)  
{  
    for (int i = 0; I < Visualtreehelper.getchildrencount (relate); i++)  
    {  
        var el = visualtreehelper.getchild (Relat E, i) as FrameworkElement;  
        if (el. GetType () = = type)  
        {  
            reselement = el;  
            return;  
        }  
        else
        {  
            findchildbytype (el, type, ref reselement);  
        }  
    }  

Hey, this method is really effective, in order to make the text color of each item different, I used the random number to create colors.

Private Color Buildcolor ()  
{  
    array.clear (colorbs, 0, colorbs.length);  
    Rand. Nextbytes (colorbs);  
    Return Color.fromrgb (Colorbs[0], colorbs[1], colorbs[2]);  
}

OK, now it's time to change the attributes of the elements in the DataTemplate.

/* has been amended/*

private void Button_click_1 (object sender, RoutedEventArgs e)  
{  
    foreach (var item in lb.) Items)  
    {  
        var el = lb. Itemcontainergenerator.containerfromitem (item) as FrameworkElement;  
        if (El!= null && el is ListBoxItem)  
        {  
            ListBoxItem lbitem = el as ListBoxItem;  
            FrameworkElement Efind = default (FrameworkElement);  
                Findchildbytype (Lbitem, typeof (TextBlock), ref efind);  
            if (Efind is TextBlock)  
            {  
                TextBlock TextBlock = Efind as TextBlock;  
                TextBlock. foreground = new SolidColorBrush (Buildcolor ());}}}  

Find out the TextBlock of each item and modify its foreground properties.

We can find the TextBlock code after a breakpoint, and then debug run. Code execution stops at the breakpoint, move the mouse over the TextBlock variable, click on the magnifying glass icon to the right of the name, and choose "WPF Tree Visualizer" from the pop-up menu. As shown in the following figure.

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.