Briefkasten Briefkasten - 2 months ago 28
C# Question

Can't retrieve dependency properties in uwp with reflection

I want to get all dependency properties of a control. I tried something like:

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

public static IEnumerable<BindingExpression> GetBindingExpressions(this FrameworkElement element)
{
IEnumerable<FieldInfo> infos = element.GetType().GetDependencyProperties();

foreach (FieldInfo field in infos)
{
if (field.FieldType == typeof(DependencyProperty))
{
DependencyProperty dp = (DependencyProperty)field.GetValue(null);
BindingExpression ex = element.GetBindingExpression(dp);

if (ex != null)
{
yield return ex;
System.Diagnostics.Debug.WriteLine("Binding found with path: “ +ex.ParentBinding.Path.Path");
}
}
}
}


Also a similar stackoverflow question. The
GetFields
method always returns an empty enumeration.

[EDIT] I executed the following lines in the universal windows platform project

typeof(CheckBox).GetFields() {System.Reflection.FieldInfo[0]}
typeof(CheckBox).GetProperties() {System.Reflection.PropertyInfo[98]}
typeof(CheckBox).GetMembers() {System.Reflection.MemberInfo[447]}


Seems to be a bug?

Answer

In UWP, the static DependencyProperty members seem to be defined as public static properties instead of public static fields. See for example the SelectionModeProperty property, which is declared as

public static DependencyProperty SelectionModeProperty { get; }

So while the expression

typeof(ListBox).GetFields(BindingFlags.Static | BindingFlags.Public)
    .Where(f => typeof(DependencyProperty).IsAssignableFrom(f.FieldType))

returns an empty IEnumerable, the expression

typeof(ListBox).GetProperties(BindingFlags.Public | BindingFlags.Static)
    .Where(p => typeof(DependencyProperty).IsAssignableFrom(p.PropertyType))

returns an IEnumerable with one element, namely the SelectionModeProperty mentioned above.

Note that you would also have to investigate all base classes to get a complete list of DependencyProperty fields/properties.