K.Warrens K.Warrens - 2 months ago 12
C# Question

Clear Textbox Controls on Window

I need to somehow loop through all controls on a UWP project's MainWindow.
My first thought was that it would be a simple foreach on my window.Controls, but this doesn't exist in UWP.

I've browsed around and found a similar question here but this code didn't seem to work either when I tried it out. It looped successfully through the entire Window, only to find out that the objects found were none at all even though I could clearly see it going through the Grid and such.

Is there a way to do this in UWP using C#? I've tried to look for a VisualTreeHelper to do it, but no success on that either. Any help appreciated!


You can use the following method from the MSDN documentation to get all your textboxes from the page:

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;
        FindChildren<T>(results, current);

It basically recursively get the children for the current item and add any item matching the requested type to the provided list.

Then, you just have to do the following somewhere in you page/button handler/...:

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

foreach(var t in allTextBoxes)
    t.Text = "Updated!";