Find a control in a WPF/Silverlight Visual Tree by name

Here’s a handy function for finding a specific child in a visual tree. This is useful for finding PART_ elements defined in a style by a ControlTemplate or DataTemplate etc.

public static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);
        string controlName = child.GetValue(Control.NameProperty) as string;
        if (controlName == name)
        {
            return child as T;
        }
        else
        {
            T result = FindVisualChildByName<T>(child, name);
            if (result != null)
                return result;
        }
    }
    return null;
}

About these ads
  1. #1 by Andrey on November 18, 2011 - 1:54 am

    Thanks!

  2. #2 by Xitij Thool on January 4, 2012 - 12:17 am

    Thank you very much, it helped a lot.

  3. #3 by Nikita on February 7, 2012 - 12:04 am

    Thanks for saving my 15 minutes!)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: