2016-09-18 98 views
0

我想获取控件的所有依赖项属性。我试过类似的东西:无法用反射检索uwp中的依赖项属性

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"); 
      } 
     } 
    } 
} 

也是一个类似的stackoverflow questionGetFields方法总是返回一个空的枚举。

[编辑]我在执行普遍windows平台项目

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

以下行似乎是一个错误?

+0

GetFields适用于我,但当然只返回在'type'中声明的那些DependencyProperty字段,而不是在任何基类中。除此之外,你使用'p.FieldType.Equals(typeof(DependencyProperty))'和'field.FieldType == typeof(DependencyProperty)'看起来很可疑。更好地写'typeof(DependencyProperty).IsAssignableFrom(f.FieldType))'。 – Clemens

+0

当我在调试器中,并执行typeof(ListBox).GetFields()时,我得到一个空列表。 – Briefkasten

回答

0

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

public static DependencyProperty SelectionModeProperty { get; } 

因此,尽管表达

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

返回一个空的IEnumerable,表达

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

返回一个IEnumerable与一个元件,即上面提到的SelectionModeProperty。

请注意,您还必须调查所有基类以获取DependencyProperty字段/属性的完整列表。