You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否遍历MAUI.NET页面中的视图/控件?

在MAUI中遍历页面所有视图与控件的解决方案

核心思路:使用VisualTreeHelper

MAUI的VisualTreeHelper类提供了遍历可视化树的官方方法,能直接绕过非公共Children属性的限制,递归获取所有层级的子元素。

实现代码示例

using Microsoft.Maui.Controls;
using Microsoft.Maui.Graphics;

public static class VisualTreeExtensions
{
    // 递归获取指定元素的所有子控件(含嵌套层级)
    public static IEnumerable<VisualElement> GetAllVisualChildren(this VisualElement parent)
    {
        if (parent == null)
            yield break;

        int childCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childCount; i++)
        {
            if (VisualTreeHelper.GetChild(parent, i) is VisualElement child)
            {
                yield return child;
                // 递归遍历当前子元素的子元素
                foreach (var grandChild in child.GetAllVisualChildren())
                {
                    yield return grandChild;
                }
            }
        }
    }
}

使用方式

在页面中直接调用扩展方法即可:

// 假设page是你的Page实例
var allControls = page.GetAllVisualChildren();
foreach (var control in allControls)
{
    // 按需处理每个控件,比如输出类型或标识
    Console.WriteLine($"控件类型:{control.GetType().Name},自动化ID:{control.AutomationId}");
}

补充说明

  • VisualTreeHelper兼容性拉满,能覆盖MAUI所有布局和控件类型,包括Grid、StackLayout、Frame这类嵌套容器。
  • 如果只需要筛选特定类型的控件,可以在遍历过程中添加类型判断:
// 只获取页面中所有Button控件
var buttons = page.GetAllVisualChildren().OfType<Button>();

内容的提问来源于stack exchange,提问作者ErikTheHack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 17:52:02