4

I got a custom Type that as a couple of fields, and I'd like to only get Dependency Properties.

Here is the code that returns all properties :

propertyInfos = myType.GetProperties();

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

I know I have to add something in parameter for GetProperties, somethg with BindingFlags.XXX but I check everything that is possible as XX and didn't find something that sounds good to me...

ASh
  • 34,632
  • 9
  • 60
  • 82
Guillaume Slashy
  • 3,554
  • 8
  • 43
  • 68
  • There are two aspects of a dependency property: The static *field* that is the real dependency property (it is of type `DependencyProperty`) and the facade property that returns the value of that static field. What do you want to have returned? – Daniel Hilgarth Sep 28 '11 at 12:01

1 Answers1

5

Dependency properties are static fields of type DependencyProperty

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

If you want to get dependency properties of parents of that control too then you can use the following method:

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;
}
ASh
  • 34,632
  • 9
  • 60
  • 82
Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131