[英]Using reflection to set a property of a control
我正在使用反射为控件分配属性,因为控件属性存储在数据库中。而且我面临以下情况的问题。
我有raddateinput控件,它具有属性DateInput.DataFormat
,当我尝试使用以下代码获取propertyinfo时,它返回为null。
ctrl.GetType().GetProperty(propertyName.Split('.').FirstOrDefault(), BindingFlags.Public | BindingFlags.Instance)
.GetType().GetProperty(propertyName.Split('.').LastOrDefault())
ctrl
是一个控件。 propertyName
为DateInput.DataFormat
我用以下代码实现了解决方案。
Private void SetProperty(Object ctrl, string propertyName, string value)
{
string name = propertyName.Split('.').First();
PropertyInfo property = ctrl.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
if (name != propertyName)
{
ctrl = property.GetValue(ctrl, null);
SetProperty(ctrl, propertyName.Replace(string.Concat(name, "."), string.Empty), value);
return;
}
TypeConverter converter = TypeDescriptor.GetConverter(property.PropertyType);
if (converter != null && converter.CanConvertFrom(typeof(String)))
property.SetValue(ctrl, converter.ConvertFrom(value), null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.