Ian GM Ian GM - 1 year ago 111
C# Question

Find all TextBox controls in UWP Page

I need to find all TextBox(es) that are on a UWP Page but having no luck. I thought it would be a simple foreach on Page.Controls but this does not exist.

Using DEBUG I am able to see, for example, a Grid. But I have to first cast the Page.Content to Grid before I can see the Children collection. I do not want to do this as it may not be a Grid at the root of the page.

Thank you in advance.

UPDATE: This is not the same as 'Find all controls in WPF Window by type'. That is WPF. This is UWP. They are different.

Answer Source

You're almost there! Cast the Page.Content to UIElementCollection, that way you can get the Children collection and be generic.

You'll have to make your method recurse and look either for Content property if element is a UIElement or Children if element is UIElementCollection.

Here's an example:

    void FindTextBoxex(object uiElement, IList<TextBox> foundOnes)
        if (uiElement is TextBox)
        else if (uiElement is Panel)
            var uiElementAsCollection = (Panel)uiElement;
            foreach (var element in uiElementAsCollection.Children)
                FindTextBoxex(element, foundOnes);
        else if (uiElement is UserControl)
            var uiElementAsUserControl = (UserControl)uiElement;
            FindTextBoxex(uiElementAsUserControl.Content, foundOnes);
        else if (uiElement is ContentControl)
            var uiElementAsContentControl = (ContentControl)uiElement;
            FindTextBoxex(uiElementAsContentControl.Content, foundOnes);

Then you call that method with:

        var tb = new List<TextBox>();
        FindTextBoxex(this, tb);
        // now you got your textboxes in tb!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download