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 question。 GetFields
方法總是返回一個空的枚舉。
[編輯]我在執行普遍windows平臺項目
typeof(CheckBox).GetFields() {System.Reflection.FieldInfo[0]}
typeof(CheckBox).GetProperties() {System.Reflection.PropertyInfo[98]}
typeof(CheckBox).GetMembers() {System.Reflection.MemberInfo[447]}
以下行似乎是一個錯誤?
GetFields適用於我,但當然只返回在'type'中聲明的那些DependencyProperty字段,而不是在任何基類中。除此之外,你使用'p.FieldType.Equals(typeof(DependencyProperty))'和'field.FieldType == typeof(DependencyProperty)'看起來很可疑。更好地寫'typeof(DependencyProperty).IsAssignableFrom(f.FieldType))'。 – Clemens
當我在調試器中,並執行typeof(ListBox).GetFields()時,我得到一個空列表。 – Briefkasten