如何在Silverlight中按名称获取DependencyProperty?

时间:2010-02-08 09:06:58

标签: c# silverlight dependency-properties

情况:我有一个字符串,表示Silverlight中TextBox的DependencyProperty的名称。例如:“TextProperty”。我需要获得对TextBox的实际TextProperty的引用,这是一个DependencyProperty。

问题:如果我得到的只是属性的名称,我如何获得对DependencyProperty(在C#中)的引用?

Silverlight中没有像DependencyPropertyDescriptor这样的东西。我似乎不得不求助于反思来获得参考。有什么建议吗?

2 个答案:

答案 0 :(得分: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 :(得分: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);

这对我有用。 :)