2011-09-28 17 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; 
}