Search code examples
c#dependencyobject

List properties of a DependencyObject?


I got a collection of custom DependencyObjects that I created. But I think that it doesn't matter wherever the DependencyObject comes from. The thing is that I'd like the list its properties but when I'm looking at the C#doc for DependencyObject I can't find anything related to the properties... :/

How can I do it ?

(nb : I got fields (string, int, etcetc..) as properties in my DependencyObject, and I got DependencyProperties too. Ultimatly I'd like to list only the DependencyProperties but it's not an obligation !)

Thx in advance and sry for my langage, im french -_- (and sry for my president too...)


Solution

  • You can do this using reflection, since DependencyProperties are (usually?) stored in public static fields of type DependencyProperty:

    private static IEnumerable<DependencyProperty> GetDependencyProperties(DependencyObject o)
    {
        return from field in o.GetType().GetFields(BindingFlags.Public | 
                                                   BindingFlags.FlattenHierarchy | 
                                                   BindingFlags.Static)
               where field.FieldType == typeof(DependencyProperty)
               select (DependencyProperty)field.GetValue(null);
    }
    

    It uses FlattenHierarchy to return all DependencyProperties, including those defined in parent classes. If you want only DependencyProperties defined directly in os class, remove the FlattenHierarchy flag.