Tips and Tricks for C# Metro developer: How to find a XAML control by its name

Today, I would like to share with you a bunch of code that is able to find the first control with a given name. With this code, you do not have to bother with XAML namespace (like with FindControl) and it will go through the entire hierarchy for you.

I use it in WorldMonger to display tutorials in top of given controls:

 

The code:

public static FrameworkElement GetChildByNameRecursively(this FrameworkElement current, string name)
{
    if (current.Name == name)
        return current;

    // App Bars
    var page = current as Page;

    if (page != null)
    {
        if (page.BottomAppBar != null)
        {
            var result = page.BottomAppBar.GetChildByNameRecursively(name);
            if (result != null)
                return result;
        }

        if (page.TopAppBar != null)
        {
            var result = page.TopAppBar.GetChildByNameRecursively(name);
            if (result != null)
                return result;
        }
    }

    // Children
    var childrenCount = VisualTreeHelper.GetChildrenCount(current);

    for (var index = 0; index < childrenCount; index++)
    {
        var frameworkElementChild = (FrameworkElement) VisualTreeHelper.GetChild(current, index);

        if (frameworkElementChild != null)
        {
            var result = frameworkElementChild.GetChildByNameRecursively(name);

            if (result != null)
                return result;
        }
    }

    return null;
}