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