遍历WPF窗体元件的两种方法

1、使用VisualTreeHelper

public static void Scan(object AComponent)
{
    if (!(AComponent is DependencyObject)) return;

    int vCount = VisualTreeHelper.GetChildrenCount((DependencyObject)AComponent);
    for (int i = 0; i < vCount; i++)
    {
        DependencyObject vChild = VisualTreeHelper.GetChild((DependencyObject)AComponent, i);
        Scan(vChild);
    }
}

2、使用反射获取未公开的属性

public static void Scan(object AComponent)
{
    PropertyInfo FI;
    MethodInfo MI;
    Visual vChild;
    int vCount;
    UIElement u;

    FI = AComponent.GetType().GetProperty("VisualChildrenCount", BindingFlags.Instance | BindingFlags.NonPublic);
    MI = AComponent.GetType().GetMethod("GetVisualChild", BindingFlags.Instance | BindingFlags.NonPublic);
    if ((FI != null) && (MI != null))
    {
        vCount = (int)FI.GetValue(AComponent, null);
        for (int i = 0; i < vCount; i++)
        {
            object[] vParams = new object[1];
            vParams[0] = i;

            vChild = (Visual)MI.Invoke(AComponent, vParams);
            Scan(vChild);
        }
    }
}


原创文章 159 获赞 11 访问量 36万+

猜你喜欢

转载自blog.csdn.net/acrodelphi/article/details/8138416