Tips and Tricks for C# Metro developer: How to find a XAML control by its name - Eternal Coding - HTML5 / Windows / Kinect / 3D development - Site Home - MSDN Blogs

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


 

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

  • Comments 3

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:

image

 

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;
}
Leave a Comment
  • Please add 3 and 3 and type the answer here:
  • Post
  • Moi je prefere quand tu codes pas avec des var. T'as fait du VB ????

  • Once again, brilliant.

  • Les var, c'est très bien dans du vrai code dans Visual Studio, où on peut passer sa souris dessus pour voir ce que c'est vraiment comme type, mais dans du code sur une page web, c'est beaucoup moins lisible :(

Page 1 of 1 (3 items)