How to enumerate all dependency properties of control?

前端 未结 5 1801
名媛妹妹
名媛妹妹 2020-12-01 21:17

I have some WPF control. For example, TextBox. How to enumerate all dependency properties of that control (like XAML editor does)?

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 21:58

    You can use reflection, via the GetFields, method to find all the public static properties on TextBox. You can then use a Linq Where clause to filter these to any of type DependencyProperty:

      var flags = BindingFlags.Static |
                  BindingFlags.FlattenHierarchy |
                  BindingFlags.Public;
      var dependencyProperties = typeof(TextBox).GetFields(flags)
                         .Where(f => f.FieldType == typeof(DependencyProperty));
    

    You can then transform this to a list of names via a Select:

      var dependencyProperties = typeof(TextBox).GetFields(flags)
                         .Where(f => f.FieldType == typeof(DependencyProperty))
                         .Select(dp => dp.Name);
    

    Note: each name has a 'Property' suffix, you can of course remove this in the above Select clause if you like.

提交回复
热议问题