2010-02-08 40 views
11

情況:我有一個字符串,表示Silverlight中TextBox的DependencyProperty的名稱。例如:「TextProperty」。我需要獲取對TextBox的實際TextProperty的引用,這是一個DependencyProperty。如何在Silverlight中通過名稱獲取DependencyProperty?

問題:如果我得到的只是屬性的名稱,如何獲得對DependencyProperty的引用(在C#中)?

類似DependencyPropertyDescriptor的東西在Silverlight中不可用。我似乎不得不求助於反思來獲得參考。有什麼建議麼?

回答

4

要回答我的問題:事實上,反射似乎是去這裏的路:

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

這做這項工作對我來說。 :)

+6

如果你的控制繼承了它的一些DependencyPropertys,如ComboBox.SelectedItemProperty這實際上是Primitives.Selector。 SelectedItemProperty或RadioButton.IsCheckedProperty,它實際上是Primitives.ToggleButton.IsCheckedProperty,那麼你將不得不使用FieldInfo field = type.GetField(「MyProperty」,BindingFlags.FlattenHierarchy);我結束了使用FieldInfo field = type.GetField(「MyProperty」,BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); – Scott 2010-06-04 03:24:46

13

你需要反思這個: -

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

用法: -

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

Ganked [。](http://yourcodeisnowmycode.lol) – Will 2011-07-15 14:38:55

相關問題