我在我的应用程序中实现了 ICustomTypeDescriptor,以便能够在运行时定义自定义属性。我的基本实现如下所示:
public class DynamicClass <T> : ICustomTypeDescriptor
{
private readonly T _object;
public DynamicClass(T trackedObject)
{
_object = trackedObject;
}
// Collection to code add dynamic properties
public KeyedCollection<string, DynamicProperty> Properties
{
get;
private set;
}
// ICustomTypeDescriptor implementation
public AttributeCollection GetAttributes()
{
return TypeDescriptor.GetAttributes(_object, true);
}
public string GetClassName()
{
return TypeDescriptor.GetClassName(_object, true);
}
public string GetComponentName()
{
return TypeDescriptor.GetComponentName(_object, true);
}
public TypeConverter GetConverter()
{
return TypeDescriptor.GetConverter(_object, true);
}
public EventDescriptor GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(_object, true);
}
public PropertyDescriptor GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(_object, true);
}
public object GetEditor(Type editorBaseType)
{
throw new NotImplementedException();
}
public EventDescriptorCollection GetEvents()
{
return TypeDescriptor.GetEvents(_object, true);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(_object, attributes, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return TypeDescriptor.GetProperties(_object, true);
}
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
return TypeDescriptor.GetProperties(_object, attributes, true);
}
public object GetPropertyOwner(PropertyDescriptor pd)
{
return _object;
}
}
问题是,现在当我使用 DynamicClass 绑定器将对象绑定到文本框时,它不再起作用。
我这样使用它:
DynamicClass<ExtensionModel> binder = new DynamicClass<ExtensionModel>(ext);
_versionLabel.DataBindings.Add("Text", binder, "SelectedVersion", false, DataSourceUpdateMode.OnPropertyChanged);
我得到了例外:“对象与目标类型不匹配。”
对象与目标类型不匹配。
在 System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target) 在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] 参数, CultureInfo 文化, Boolean skipVisibilityChecks) 在 System.Reflection.RuntimeMethodInfo.Invoke( Object obj、BindingFlags invokeAttr、Binder binder、Object[] 参数、CultureInfo 文化)
在 System.ComponentModel.ReflectEventDescriptor.AddEventHandler(Object 组件,委托值) 在 System.ComponentModel.ReflectPropertyDescriptor.AddValueChanged(Object 组件,EventHandler 处理程序) 在 System.Windows.Forms.BindToObject.CheckBinding() 在 System.Windows.Forms.Binding .SetListManager(BindingManagerBase bindingManagerBase) 在 System.Windows.Forms.ListManagerBindingsCollection.AddCore(Binding dataBinding) 在 System.Windows.Forms.BindingsCollection.Add(Binding binding) 在 System.Windows.Forms.BindingContext.UpdateBinding(BindingContext newBindingContext, Binding binding ) 在 System.Windows.Forms.Control.UpdateBindings()
如果我使用 ext 对象而不是 binder,则绑定有效。我错过了 ICustomTypeDescriptor 实现中的某些内容吗?