在UWP页面中查找所有TextBox控件

Ian*_* GM 6 c# win-universal-app

我需要找到UWP页面上但没有运气的所有TextBox.我认为这将是Page.Controls上的一个简单的foreach,但这不存在.

使用DEBUG我可以看到,例如,一个网格.但是我必须首先将Page.Content转换为Grid才能看到Children集合.我不想这样做,因为它可能不是页面根目录中的网格.

先感谢您.

更新:这与'按类型查找WPF窗口中的所有控件'不同.那是WPF.这是UWP.它们是不同的.

Vin*_*ent 8

您还可以使用VisualTreeHelper 文档中的以下通用方法来获取给定类型的所有子控件:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

然后,您只需在某处执行以下操作即可获取元素:

var allTextBoxes    = new List<TextBox>();
FindChildren(allTextBoxes, this);
Run Code Online (Sandbox Code Playgroud)


Arn*_*eil 6

你快到了!将Page.Content转换为UIElementCollection,这样您就可以获得Children集合并且是通用的.

如果element是UIElement,那么你必须使你的方法递归并查找Content属性,或者如果element是UIElementCollection,则查找子元素.

这是一个例子:

    void FindTextBoxex(object uiElement, IList<TextBox> foundOnes)
    {
        if (uiElement is TextBox)
        {
            foundOnes.Add((TextBox)uiElement);
        }
        else if (uiElement is Panel)
        {
            var uiElementAsCollection = (Panel)uiElement;
            foreach (var element in uiElementAsCollection.Children)
            {
                FindTextBoxex(element, foundOnes);
            }
        }
        else if (uiElement is UserControl)
        {
            var uiElementAsUserControl = (UserControl)uiElement;
            FindTextBoxex(uiElementAsUserControl.Content, foundOnes);
        }
        else if (uiElement is ContentControl)
        {
            var uiElementAsContentControl = (ContentControl)uiElement;
            FindTextBoxex(uiElementAsContentControl.Content, foundOnes);
        }
        else if (uiElement is Decorator)
        {
            var uiElementAsBorder = (Decorator)uiElement;
            FindTextBoxex(uiElementAsBorder.Child, foundOnes);
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后用以下方法调用该方法:

        var tb = new List<TextBox>();
        FindTextBoxex(this, tb);
        // now you got your textboxes in tb!
Run Code Online (Sandbox Code Playgroud)