清除 Window 上的文本框控件

Clear Textbox Controls on Window

我需要以某种方式循环访问 UWP 项目 MainWindow 上的所有控件。 我的第一个想法是,这将是我的 window.Controls 上的一个简单的 foreach,但这在 UWP 中不存在。

我浏览了一下,发现了一个类似的问题,但是当我尝试时,这段代码似乎也不起作用。它成功地遍历了整个 Window,却发现找到的对象根本就是 none,尽管我可以清楚地看到它穿过 Grid 等等。

有没有办法在 UWP 中使用 C# 执行此操作?我试图寻找一个 VisualTreeHelper 来做到这一点,但也没有成功。任何帮助表示赞赏!

简单的方法就是 TextBox.Text = String.Empty; 视图中的每个文本框。

您可以使用 MSDN documentation 中的以下方法从页面中获取所有文本框:

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);
    }
}

它基本上递归地获取当前项目的子项,并将与请求类型匹配的任何项目添加到提供的列表中。

然后,您只需要在 page/button handler/... 的某处执行以下操作:

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

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

您可以使用下面的代码找到控件。

 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;
    }

并且可以清除文本框。

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