How to get a DependencyProperty by name in Silverlight?

我的未来我决定 提交于 2019-12-23 07:09:47

问题


Situation: I have a string that represents the name of a DependencyProperty of a TextBox in Silverlight. For example: "TextProperty". I need to get a reference to the actual TextProperty of the TextBox, which is a DependencyProperty.

Question: how do I get a reference to a DependencyProperty (in C#) if all I got is the name of the property?

Things like DependencyPropertyDescriptor are not available in Silverlight. It seems I have to resort to reflection to get the reference. Any suggestions?


回答1:


You will need reflection for this:-

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

Usage:-

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



回答2:


To answer my own question: Indeed, reflection seems to be the way to go here:

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

This does the job for me. :)



来源:https://stackoverflow.com/questions/2220474/how-to-get-a-dependencyproperty-by-name-in-silverlight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!