Thursday, July 22, 2010

Overriding ExpandableObjectConverter::GetProperties

Today I was faced with a BrowsableAttribute problem:

I had a collection that I needed to be able to select from a PropertyGrid, but also be able to edit the items and their properties with a DataGridView. I wanted the PropertyGrid to show only the item name in an expandable control and to be able to edit all the items property in the DataGridView.

When using BrowsableAttribute I had a problem that each time I would have to set the value according to the requesting control. I solved this by overriding ExpandableObjectConverter::GetProperties. I went over the PropertyDescriptorCollection and removed each property I didn't want:

public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
PropertyDescriptorCollection collection = base.GetProperties(context, value, attributes);
PropertyDescriptor[] final = new PropertyDescriptor[1];
foreach (PropertyDescriptor descriptor in collection)
{
if (descriptor.Name == "ItemName")
final[0] = descriptor;
}
return new PropertyDescriptorCollection(final);
}

Now when binding the list to DataGridView I would see all the properties, and when expanding the list in PropertyGrid I would see only the Item Name Property.