获取控件的所有依赖项属性

时间:2014-12-22 13:45:28

标签: c# wpf dependency-properties

我需要确定窗口上的控件是否声明了特定的依赖项属性。以下是带有DP DemandRole的按钮示例。可以为各种控件类型声明DP,而不仅仅是按钮。我试图枚举窗口上的所有控件,只返回那些声明了DP DemandRole的控件。

<Button x:Name="_reset"
        sec:SecurityAction.DemandRole="Admin,Engineer,SuperUser,Technician,Supervisor" 
        Content="_Reset"
        Visibility="Visible"
        Command="{Binding ResetPasswordCommand}" />

我可以获取特定类型的依赖项属性,但只返回该类型的属性,并且包含我为控件定义的DP。

static IEnumerable<FieldInfo> GetDependencyProperties(Type type)
{
        var dependencyProperties = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
                                       .Where(p => p.FieldType.Equals(typeof(DependencyProperty)));
        return dependencyProperties;
    }

知道如何在控件的特定实例上获取所有DP吗?

谢谢,

兰斯

2 个答案:

答案 0 :(得分:2)

我在Visual Studio论坛的Getting list of all dependency/attached properties of an Object页面上找到了这个代码示例。我无法保证它能够正常工作,但它会出现在&#39;帮助了原来的问题作者。

public static class DependencyObjectHelper
{
    public static List<DependencyProperty> GetDependencyProperties(Object element)
    {
        List<DependencyProperty> properties = new List<DependencyProperty>();
        MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element);
        if (markupObject != null)
        {
            foreach (MarkupProperty mp in markupObject.Properties)
            {
                if (mp.DependencyProperty != null)
                {
                    properties.Add(mp.DependencyProperty);
                }
            }
        }

        return properties;
    }

    public static List<DependencyProperty> GetAttachedProperties(Object element)
    {
        List<DependencyProperty> attachedProperties = new List<DependencyProperty>();
        MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element);
        if (markupObject != null)
        {
            foreach (MarkupProperty mp in markupObject.Properties)
            {
                if (mp.IsAttached)
                {
                    attachedProperties.Add(mp.DependencyProperty);
                }
            }
        }

        return attachedProperties;
    }
}

如果这些扩展方法没有帮助,链接页面上还有其他示例。


更新&gt;&gt;&gt;

我刚刚在Stack Overflow上找到了这个问题,这也可能会有所帮助:

  

How to enumerate all dependency properties of control?

答案 1 :(得分:1)

未经测试,但我猜你需要BindingFlags.FlattenHierarchy标志。

static IEnumerable<FieldInfo> GetDependencyProperties(Type type)
{
     var dependencyProperties = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy)
                                       .Where(p => p.FieldType.Equals(typeof(DependencyProperty)));
     return dependencyProperties;
}

如果这不起作用,则需要递归调用type.BaseType.GetFields,直到BaseType返回null并连接所有字段。

相关问题