我有一个实现ICustomTypeDescriptor的模型。这是因为我希望能够添加自定义属性...不在对象中并将它们绑定到文本框。奇怪的是,绑定对PropertyGrid很有用,但对文本框不起作用。
此代码有效:
DynamicClass<ExtensionModel> binder = new DynamicClass<ExtensionModel>(ext);
propertyGrid1.SelectedObject = binder;
但不是他的那个:
var binder = new DynamicClass<ExtensionModel>(ext);
_versionLabel.DataBindings.Add("Text", binder, "SelectedVersion", false, DataSourceUpdateMode.OnPropertyChanged);
在这种情况下,我得到的Object与目标类型不匹配。例外。如果我在绑定中加入ext而不是binder,它可以正常工作。
文本框绑定功能有问题吗?
我的DynamicClass代码是:
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
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return TypeDescriptor.GetAttributes(_object, true);
}
string ICustomTypeDescriptor.GetClassName()
{
return TypeDescriptor.GetClassName(_object, true);
}
string ICustomTypeDescriptor.GetComponentName()
{
return TypeDescriptor.GetComponentName(_object, true);
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return TypeDescriptor.GetConverter(_object, true);
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(_object, true);
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(_object, true);
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(_object, editorBaseType, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return TypeDescriptor.GetEvents(_object, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(_object, attributes, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return TypeDescriptor.GetProperties(_object, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
return TypeDescriptor.GetProperties(_object, attributes, true);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return _object;
}
}
答案 0 :(得分:1)
这里存在一个基本问题,即您为实际对象(ExtensionModel
)提供描述符,但组合框只知道包装器({{1因此,将试图在错误的对象上调用方法。您可以通过将描述符包装在为您交换对象的内容中来避免这种情况;如:
DynamicClass<T>