在窗口

时间:2016-11-18 10:26:44

标签: c# uwp uwp-xaml

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

我浏览了周围并发现了一个类似的问题here但是这个代码在我试用时似乎没有用。它在整个Window中成功循环,但发现找到的对象完全没有,即使我能清楚地看到它通过Grid等等。

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

3 个答案:

答案 0 :(得分:2)

您可以使用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);
    }
}

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

然后,您只需在页面/按钮处理程序/...:

中的某处执行以下操作
var allTextBoxes    = new List<TextBox>();
FindChildren(allTextBoxes, this);

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您可以使用以下代码查找控件。

 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;
相关问题