K.Warrens
K.Warrens

Reputation: 35

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!

Upvotes: 1

Views: 450

Answers (3)

Jitendra.Suthar
Jitendra.Suthar

Reputation: 110

You can use below code to find control.

 public static T FindChild<T>(DependencyObject depObj, string childName)
       where T : DependencyObject
    {
        // Confirm parent and childName are valid. 
        if (depObj == null) return null;

        // success case
        if (depObj is T && ((FrameworkElement)depObj).Name == childName)
            return depObj as T;

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);

            //DFS
            T obj = FindChild<T>(child, childName);

            if (obj != null)
                return obj;
        }

        return null;
    }

and can clear text box.

  TextBox txtBox1= FindChild<TextBox>(this, "txtBox1");
        if (txtBox1!= null)
            txtBox1.Text= String.Empty;

Upvotes: 0

Vincent
Vincent

Reputation: 3746

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;
            results.Add(asType);
        }
        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!";
}

Upvotes: 2

Kuba
Kuba

Reputation: 226

Simple way is just TextBox.Text = String.Empty; for every TextBox in View.

Upvotes: 0

Related Questions