无法使用反射检索 uwp 中的依赖属性

Can't retrieve dependency properties in uwp with reflection

我想获取控件的所有依赖属性。我试过类似的东西:

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

public static IEnumerable<BindingExpression> GetBindingExpressions(this FrameworkElement element)
{
    IEnumerable<FieldInfo> infos = element.GetType().GetDependencyProperties();

    foreach (FieldInfo field in infos)
    {
        if (field.FieldType == typeof(DependencyProperty))
        {
            DependencyProperty dp = (DependencyProperty)field.GetValue(null);
            BindingExpression ex = element.GetBindingExpression(dp);

            if (ex != null)
            {
                yield return ex;
                System.Diagnostics.Debug.WriteLine("Binding found with path: “ +ex.ParentBinding.Path.Path");
            }
        }
    }
}

还有一个类似的Whosebug GetFields 方法总是 returns 空枚举。

[编辑] 我在通用 windows 平台项目中执行了以下几行

typeof(CheckBox).GetFields()    {System.Reflection.FieldInfo[0]}
typeof(CheckBox).GetProperties()    {System.Reflection.PropertyInfo[98]}
typeof(CheckBox).GetMembers()   {System.Reflection.MemberInfo[447]}

似乎是一个错误?

在 UWP 中,静态 DependencyProperty 成员似乎被定义为 public 静态属性而不是 public 静态字段。例如,参见 SelectionModeProperty 属性,它被声明为

public static DependencyProperty SelectionModeProperty { get; }

所以当表达式

typeof(ListBox).GetFields(BindingFlags.Static | BindingFlags.Public)
    .Where(f => typeof(DependencyProperty).IsAssignableFrom(f.FieldType))

returns 一个空的 IEnumerable,表达式

typeof(ListBox).GetProperties(BindingFlags.Public | BindingFlags.Static)
    .Where(p => typeof(DependencyProperty).IsAssignableFrom(p.PropertyType))

returns一个IEnumerable,只有一个元素,即上面提到的SelectionModeProperty

请注意,您还必须调查所有基础 类 以获得 DependencyProperty fields/properties 的完整列表。