这个问题(连同它的答案)解释了为什么您不能轻松地将 DataGridView 绑定到接口类型并获取从基本接口继承的属性的列。
建议的解决方案是实现自定义 TypeConverter。我的尝试如下。但是,创建绑定到 ICamel 的 DataSource 和 DataGridView 仍然只会产生一列(Humps)。我不认为.NET 正在使用我的转换器来决定它可以为 ICamel 看到哪些属性。我究竟做错了什么?
[TypeConverter(typeof(MyConverter))]
public interface IAnimal
{
string Name { get; set; }
int Legs { get; set; }
}
[TypeConverter(typeof(MyConverter))]
public interface ICamel : IAnimal
{
int Humps { get; set; }
}
public class MyConverter : TypeConverter
{
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
if(value is Type && (Type)value == typeof(ICamel))
{
List<PropertyDescriptor> propertyDescriptors = new List<PropertyDescriptor>();
foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(ICamel)))
{
propertyDescriptors.Add(pd);
}
foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(IAnimal)))
{
propertyDescriptors.Add(pd);
}
return new PropertyDescriptorCollection(propertyDescriptors.ToArray());
}
return base.GetProperties(context, value, attributes);
}
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
}
}