在 UWP 页面中查找所有 TextBox 控件 [英] Find all TextBox controls in UWP Page

查看:22
本文介绍了在 UWP 页面中查找所有 TextBox 控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to find all TextBox(es) that are on a UWP Page but having no luck. I thought it would be a simple foreach on Page.Controls but this does not exist.

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

Using DEBUG I am able to see, for example, a Grid. But I have to first cast the Page.Content to Grid before I can see the Children collection. I do not want to do this as it may not be a Grid at the root of the page.

提前致谢.

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

UPDATE: This is not the same as 'Find all controls in WPF Window by type'. That is WPF. This is UWP. They are different.

推荐答案

大功告成!将 Page.Content 转换为 UIElementCollection,这样您就可以获得 Children 集合并变得通用.

You're almost there! Cast the Page.Content to UIElementCollection, that way you can get the Children collection and be generic.

如果元素是 UIElement,则必须使方法递归并查找 Content 属性,如果元素是 UIElementCollection,则查找 Children 属性.

You'll have to make your method recurse and look either for Content property if element is a UIElement or Children if element is 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);
        }
    }

然后你调用这个方法:

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

这篇关于在 UWP 页面中查找所有 TextBox 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆