通过反射给控件,或者对象的的属性设计值的时候,会遇到类型的转换问题
如果属性的类型只有几种的情况,只用switch就可以了
但是如果属性类型的情况比较多,那么就得找其它办法了.
Binding类中给我们一个比较安全的办法
如果属性的类型只有几种的情况,只用switch就可以了
但是如果属性类型的情况比较多,那么就得找其它办法了.
Binding类中给我们一个比较安全的办法
object instancevalue;//要给控件绑定的对象的值
Control bindcontrol;
System.Type controltype = bindcontrol.GetType();
PropertyInfo[] controlpro = controltype.GetProperties();
foreach (PropertyInfo tpi in controlpro)
{
if (tpi.Name == controlproperty)//controlproperty指到要绑定到的控件的属性名
{
Type controlpropertytype = tpi.PropertyType;//这个控件属性要求的类型,
//经过类型转换的值
object convertedprovalue= Convert.ChangeType(instancevalue, controlpropertytype);
tpi.SetValue(bindcontrol, convertedprovalue, null);
//if (tpi.Name == "Text")
// tpi.SetValue(bindcontrol, instancevalue.ToString(), null);
//else
// tpi.SetValue(bindcontrol, instancevalue, null);
}
else
continue;
}
//这是从Binding的类中反射得来的,如果以上代码没有能完成转换的任务,可以参考以下的代码
TypeConverter converter = TypeDescriptor.GetConverter(value.GetType());
if ((converter != null) && converter.CanConvertTo(propertyType))
{
return converter.ConvertTo(value, propertyType);
}
if (value is IConvertible)
{
obj2 = Convert.ChangeType(value, propertyType);
if (obj2.GetType().IsSubclassOf(propertyType) || (obj2.GetType() == propertyType))
{
return obj2;
}
}
Control bindcontrol;
System.Type controltype = bindcontrol.GetType();
PropertyInfo[] controlpro = controltype.GetProperties();
foreach (PropertyInfo tpi in controlpro)
{
if (tpi.Name == controlproperty)//controlproperty指到要绑定到的控件的属性名
{
Type controlpropertytype = tpi.PropertyType;//这个控件属性要求的类型,
//经过类型转换的值
object convertedprovalue= Convert.ChangeType(instancevalue, controlpropertytype);
tpi.SetValue(bindcontrol, convertedprovalue, null);
//if (tpi.Name == "Text")
// tpi.SetValue(bindcontrol, instancevalue.ToString(), null);
//else
// tpi.SetValue(bindcontrol, instancevalue, null);
}
else
continue;
}
//这是从Binding的类中反射得来的,如果以上代码没有能完成转换的任务,可以参考以下的代码
TypeConverter converter = TypeDescriptor.GetConverter(value.GetType());
if ((converter != null) && converter.CanConvertTo(propertyType))
{
return converter.ConvertTo(value, propertyType);
}
if (value is IConvertible)
{
obj2 = Convert.ChangeType(value, propertyType);
if (obj2.GetType().IsSubclassOf(propertyType) || (obj2.GetType() == propertyType))
{
return obj2;
}
}
本文介绍了一种使用反射机制进行属性绑定的方法,并讨论了在不同属性类型之间进行安全类型转换的技术细节。通过示例代码展示了如何利用Binding类来实现属性绑定,确保不同类型之间的正确转换。

1398

被折叠的 条评论
为什么被折叠?



