2010-02-08 4 views
11

Situation: J'ai une chaîne qui représente le nom d'un DependencyProperty d'un TextBox dans Silverlight. Par exemple: "TextProperty". J'ai besoin d'obtenir une référence à la TextProperty réelle de la TextBox, qui est un DependencyProperty. Question: comment obtenir une référence à DependencyProperty (en C#) si tout ce que j'ai obtenu est le nom de la propriété?Comment obtenir un DependencyProperty par son nom dans Silverlight?

Des choses comme DependencyPropertyDescriptor ne sont pas disponibles dans Silverlight. Il semble que je doive recourir à la réflexion pour obtenir la référence. Aucune suggestion?

Répondre

4

Pour répondre à ma propre question: En effet, la réflexion semble être la voie à suivre ici:

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); 

Cela fait le travail pour moi. :)

+6

Si votre contrôle hérite certains de ses DependencyPropertys, comme ComboBox.SelectedItemProperty qui est en fait Primitives.Selector. SelectedItemProperty ou RadioButton.IsCheckedProperty qui est en fait Primitives.ToggleButton.IsCheckedProperty alors vous devrez utiliser FieldInfo field = type.GetField ("MyProperty", BindingFlags.FlattenHierarchy); J'ai fini par utiliser FieldInfo field = type.GetField ("MyProperty", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); – Scott

13

Vous aurez besoin de réflexion pour cela: -

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; 
} 

Utilisation: -

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

Ganked [.] (Http://yourcodeisnowmycode.lol) – Will

Questions connexes