繁体   English   中英

清除窗口上的文本框控件

[英]Clear Textbox Controls on Window

我需要以某种方式遍历UWP项目的MainWindow上的所有控件。 我最初的想法是,这将是在我的window.Controls上的一个简单的foreach,但这在UWP中并不存在。

我浏览了一下,在这里发现了一个类似的问题但是当我尝试该代码时,该代码似乎也不起作用。 它成功地遍历了整个Window,只是发现所找到的对象根本没有,即使我可以清楚地看到它正在穿过Grid等。

有没有办法使用C#在UWP中做到这一点? 我试图寻找一个VisualTreeHelper来做到这一点,但无论如何都没有成功。 任何帮助表示赞赏!

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

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

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

简单的方法就是TextBox.Text = String.Empty; 对于View中的每个TextBox。

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

 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM