Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to interface and displaying properties in base interface

This question (along with its answer) explains why you can't easily bind a DataGridView to an interface type and get columns for properties inherited from a base interface.

The suggested solution is to implement a custom TypeConverter. My attempt is below. However, creating a DataSource and DataGridView bound to ICamel still only results in one column (Humps). I don't think that my converter is being used by .NET to decide which properties it can see for ICamel. What am I doing wrong?

[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;
    }
}
like image 531
spatulon Avatar asked Oct 15 '22 15:10

spatulon


1 Answers

DataGridView does not use TypeConverter; PropertyGrid uses TypeConverter.

If it relates to list-controls like DataGridView, then the other answer is wrong.

To provide custom properties on a list, you need one of:

  • ITypedList on the data-source
  • TypeDescriptionProvider on the type

Both are non-trivial.

like image 150
Marc Gravell Avatar answered Oct 20 '22 17:10

Marc Gravell