Find all TextBox controls on the UWP page

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

Using DEBUG, I can see, for example, Grid. But before I see the Children collection, I must first transfer the page. Grid contract. I do not want to do this, because it may not be a Grid at the root of the page.

Thanks in advance.

UPDATE: this is not the same as "Find all controls in a WPF window by type." This is WPF. This is UWP. They are different.

+5
source share
3 answers

! . UIElementCollection, Children .

Content, UIElement Children, UIElementCollection.

:

    void FindTextBoxex(object uiElement, IList<TextBox> foundOnes)
    {
        if (uiElement is TextBox)
        {
            foundOnes.Add((TextBox)uiElement);
        }
        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);
        }
        else if (uiElement is Decorator)
        {
            var uiElementAsBorder = (Decorator)uiElement;
            FindTextBoxex(uiElementAsBorder.Child, foundOnes);
        }
    }

:

        var tb = new List<TextBox>();
        FindTextBoxex(this, tb);
        // now you got your textboxes in tb!
+6

VisualTreeHelper, :

internal static void FindChildren<T>(List<T> results, DependencyObject startNode)
  where T : DependencyObject
{
    int count = VisualTreeHelper.GetChildrenCount(startNode);
    for (int i = 0; i < count; i++)
    {
        DependencyObject current = VisualTreeHelper.GetChild(startNode, i);
        if ((current.GetType()).Equals(typeof(T)) || (current.GetType().GetTypeInfo().IsSubclassOf(typeof(T))))
        {
            T asType = (T)current;
            results.Add(asType);
        }
        FindChildren<T>(results, current);
    }
}

, , .

- , :

var allTextBoxes    = new List<TextBox>();
FindChildren(allTextBoxes, this);
+4

In my opinion, you can do it the same way as in WPF. Because UWP uses basically the same XAML as WPF.

So please check the answer to the same question about WPF

+2
source

All Articles