2011-09-28 46 views
4

我得到一个自定义类型,作为几个字段,我只想得到依赖属性。使用反射获取DependencyProperties(Type.GetProperties)?

这里是返回所有属性代码:

propertyInfos = myType.GetProperties(); 

foreach (PropertyInfo propertyInfo in propertyInfos) 
{ 
    Console.WriteLine(propertyInfo.Name); 
} 

我知道我必须在参数的GetProperties,somethg与BindingFlags.XXX添加的东西,但我检查一切都是可能的XX并没有找到的东西,听起来不错,我...

+0

有一个依赖属性的两个方面:静态*项*那才是真正的依赖属性(它是类型'DependencyProperty' )和返回该静态字段的值的facade属性。你想要返回什么? –

回答

5

依赖属性是如果你想获得式DependencyProperty

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

的静态字段该控制的父母的依赖属性太那么你可以使用下面的方法:

static IEnumerable<FieldInfo> GetDependencyProperties(Type type) 
{ 
    var properties = type.GetFields(BindingFlags.Static | BindingFlags.Public) 
         .Where(f=>f.FieldType == typeof(DependencyProperty)); 
    if (type.BaseType != null) 
     properties = properties.Union(GetDependencyProperties(type.BaseType)); 
    return properties; 
}