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;
}

  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 to Xitij Thool Cancel reply