Archive for April, 2009

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

Advertisements

3 Comments