Get a descendant FrameworkElement based on its name.

Brian Lagunas / Wednesday, August 22, 2012

Back in July I wrote a blog post that showed how to add a checkbox to the row selector of the XamGrid and data bind to it.  The demo was written in WPF and used a method that exists inside a Utilities class.  Specifically Infragistics.Windows.Utilities.GetDescendantFromName.  I had a comment that asked me where the same Utilities.GetDescendantFromName method existed in Silverlight.  Well, I soon discovered that it didn’t.  We do not have a Utilities class for Silverlight.  No big deal though, because this is actually a very well known method.  You have probably seen it, or variations of it, on the web.  So if you are in Silverlight and trying to implement the Utilities.GetDescendantFromName method, use this implementation instead.

/// <summary>
/// Gets a descendant FrameworkElement based on its name.
/// </summary>
/// <returns>A descendant FrameworkElement with the specified name or null if not found.</returns>
public static FrameworkElement GetDescendantFromName(DependencyObject parent, string name)
{
    int count = VisualTreeHelper.GetChildrenCount(parent);

    if (count < 1)
        return null;

    FrameworkElement fe;

    for (int i = 0; i < count; i++)
    {
        fe = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;
        if (fe != null)
        {
            if (fe.Name == name)
                return fe;

            fe = GetDescendantFromName(fe, name);
            if (fe != null)
                return fe;
        }
    }

    return null;
}