绑定到接口并在基接口中显示属性

spa*_*lon 5 c# datasource datagridview interface

这个问题(及其答案)解释了为什么您不能轻松地将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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 3

DataGridView不使用TypeConverterPropertyGrid使用TypeConverter.

如果它与像这样的列表控件相关DataGridView,那么另一个答案是错误的。

要在列表上提供自定义属性,您需要以下之一:

  • ITypedList在数据源上
  • TypeDescriptionProvider在类型上

两者都非同小可。