2016-09-18 103 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字段/屬性的完整列表。