如何最轻松地确定一个属性是否是依赖属性?

3
4个回答

4

依赖属性在其定义的类上有相应的静态字段。请查看DataGridTextColumn类的字段部分。


2
在大多数情况下,您可以通过检查是否存在命名为 FooProperty 的静态字段类型为 DependencyProperty 来检测属性 Foo 是否为 DP。然而,这只是一个约定,并不能保证所有的依赖属性都会遵循这种模式。

1

已经有答案了,我知道。在“TextBlock”中,“Text”属性是一个依赖属性,你可以通过Intellisense显示静态字段来确定:

TextBlock.TextProperty


0
这是一个扩展方法,它评估属性的值并返回相应的DependencyProperty:
    public static bool TryEvaluateProperty(this FrameworkElement fe, string property, out object value, out DependencyProperty dp)
    {
        value = default;
        dp = default;

        var feType = fe.GetType();
        var propertyInfo = feType.GetProperty(property, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);

        if (propertyInfo == null) return false;

        value = propertyInfo.GetValue(fe);

        var dpName = property + "Property"; //ASSUMPTION: Definition uses DependencyProperty naming convention

        while (feType != null)
        {
            var dpField = feType.GetField(dpName, BindingFlags.Static | BindingFlags.Public);

            if (dpField != null)
            {
                dp = dpField.GetValue(null) as DependencyProperty; //use obj==null for static field
                break;
            }

            feType = feType.BaseType;
        }

        return true;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接