Jer*_*nNL 11 c# silverlight dependency-properties
情况:我有一个字符串,表示Silverlight中TextBox的DependencyProperty的名称.例如:"TextProperty".我需要获得TextBox的实际TextProperty的引用,它是DependencyProperty.
问题:如果我得到的只是属性的名称,我如何获得对DependencyProperty(在C#中)的引用?
诸如DependencyPropertyDescriptor之类的东西在Silverlight中不可用.我似乎不得不求助于反思来获得参考.有什么建议?
Ant*_*nes 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;
}
Run Code Online (Sandbox Code Playgroud)
用法:-
var dp = GetDependencyProperty(typeof(TextBox), "TextProperty");
Run Code Online (Sandbox Code Playgroud)
回答我自己的问题:确实,反思似乎是解决问题的方法:
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);
Run Code Online (Sandbox Code Playgroud)
这对我来说很有效。:)