views:

548

answers:

2

Situation: I have a string that represents the name of a DependencyProperty of a TextBox in Silverlight. For example: "TextProperty". I need to get a reference to the actual TextProperty of the TextBox, which is a DependencyProperty.

Question: how do I get a reference to a DependencyProperty (in C#) if all I got is the name of the property?

Things like DependencyPropertyDescriptor are not available in Silverlight. It seems I have to resort to reflection to get the reference. Any suggestions?

A: 

To answer my own question: Indeed, reflection seems to be the way to go here:

Control control = <create some control with a property called MyProperty here>;
Type type = control.GetType();    
FieldInfo field = type.GetField("MyProperty");
DependencyProperty dp = (DependencyProperty)field.GetValue(control);

This does the job for me. :)

JeroenNL
If your control inherits some of its DependencyPropertys, like ComboBox.SelectedItemProperty which is actually Primitives.Selector.SelectedItemProperty or RadioButton.IsCheckedProperty which is actually Primitives.ToggleButton.IsCheckedProperty then you will have to use FieldInfo field = type.GetField("MyProperty", BindingFlags.FlattenHierarchy); I ended up using FieldInfo field = type.GetField("MyProperty", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
Scott
A: 

You will need reflection for this:-

 public static DependencyProperty GetDependencyProperty(Type type, string name)
 {
     FieldInfo fieldInfo = type.GetField(name, BindingFlags.Public | BindingFlags.Static);
     return (fieldInfo != null) ? (DependencyProperty)fieldInfo.GetValue(null) : null;
 }

Usage:-

 var dp = GetDependencyProperty(typeof(TextBox), "TextProperty");
AnthonyWJones