WPF在C Sharp中使用反射分配控件属性 [英] WPF Assigning control Properties using reflection in c sharp

查看:109
本文介绍了WPF在C Sharp中使用反射分配控件属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在尝试创建一个应用程序,该应用程序从从XML文件读取的数据中创建对象.
通过反射,我设法创建了所需的对象并分配了一些属性,例如原始类型和ENUM types.
对于基本类型,其中property是一个Dictionary条目,其Property名称要更改,值要设置

Hi,
I am trying to create an application that creates objects from data that is read from an XML file.
Using reflection I have managed to create the objects I need and assign some of the properties like primitive types and ENUM types.
For primitive types where property is a Dictionary entry with the Property name to change and the value to set

type.GetProperty((string)property.Key).SetValue(control, Convert.ChangeType((string)property.Value, propertyType, null), null);


以及ENUM types


and for ENUM types

object desiredPropertyValue = Enum.Parse(propertyType, (string)property.Value);
                    propertyInfo.SetValue(control, desiredPropertyValue, null);


我遇到的问题是,我似乎找不到一种设置其他类型的属性的方法,例如Fontweight,fontfamily,Margin和许多其他我认为这些都是类型结构的属性,任何帮助将不胜感激
谢谢.


The problem I have is that I can''t seem to find a way to set other types of properties like Fontweight, fontfamily, Margin and many others I think these are of type structure, any help would be appreciated
Thank you.

推荐答案

使用哪种类型的属性没有区别.

您的错误是Convert. (此类困扰着CodeProject查询者.如何滥用这种类型的代码感染所有人?)您可能无法理解所有类型都继承自System.Object(参数类型为System.Reflection.PropertyInfo.SetValue).在此方法中,甚至原始类型和枚举类型都用作对象(通过boxing;您需要非常了解装箱方法).

您需要直接使用值:

There is no difference what type of the property you use.

Your mistake is Convert. (This class haunts CodeProject inquirers. How infected everyone with this abusing this type?) You probably fail to understand that all types inherit from System.Object, which is a parameter type of System.Reflection.PropertyInfo.SetValue. Even primitive and enumeration types are used as object (through boxing; you need to understand very well how boxing works) in this method.

You need to use value directly:

PropertyInfo piMargin = //...
PropertyInfo piFont = //... why Font Weight or Family? use the whole font
PropertyInfo piWidth = //... just to demonstrate property of the primitive type
int newWidth = //...

//...

piMargin.SetValue(myObject, new Margin( /* ... */ ), null);
piFont.SetValue(myObject, new Font(( /* ... */ ), null);
piWidth.SetValue(myObject, newWidth, null); //newWidth is boxed at the call



—SA



—SA


这篇关于WPF在C Sharp中使用反射分配控件属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆