如何在Silverlight中按名称获取DependencyProperty?
情况:我有一个字符串,表示Silverlight中TextBox的DependencyProperty的名称。 例如:“TextProperty”。 我需要获得TextBox的实际TextProperty的引用,它是DependencyProperty。
问题:如果我得到的只是属性的名称,我如何获得对DependencyProperty(在C#中)的引用?
诸如DependencyPropertyDescriptor之类的东西在Silverlight中不可用。 我似乎不得不求助于反思来获得参考。 有什么建议?
你需要反思: –
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");
回答我自己的问题:确实,反思似乎是要走的路:
Control control = ; Type type = control.GetType(); FieldInfo field = type.GetField("MyProperty"); DependencyProperty dp = (DependencyProperty)field.GetValue(control);
这对我来说很重要。 🙂