Tuesday, July 25, 2006

Customized display of collection data in a PropertyGrid

If you assign array in PropertyGrid ,you'll see that propertyGrid display all the objects contained within that array.
for e.g
- Person
Name
Address
Age

An object may provide custom information about itself by implementing an interface ICustomTypeDescriptor. This interface can be used to provide dynamic type information. This is the case for a Collection object to return its content appearing as properties in a PropertyGrid

If ICustomTypeDescriptor is not used, then a static TypeDescriptor will be used at runtime, which provides type information based on the meta data obtained via reflection.

TypeConverters can also be used for more complex objects, such as classes, where the properties can be exposed at design-time. One of the ways to achieve this is through the ExpandableObjectConverter class. This class is a TypeConverter that creates a plus/minus sign box that can expand/contract the group of properties within that class.

Public Class HighlightingTypeConverter : ExpandableObjectConverter

Than you can override ConvertFrom and ConvertTo function . ConvertFrom Converts string to Highlighting class object and ConvertTo Converts highlighting class object to string value.

public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)

public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)

What is most important in ConvertFrom is that the value is converted to a string array by using the Split() method to break apart the string. We've defined the "@" character as a separator for the text. It can be a single character, multiple characters, or different characters separating each field.

string[] strValues = value.ToString().Split("@".ToCharArray())

Then you can assign this splited value to the properties of your class

ButtonAttribute btnsettings = new ButtonAttribute ();
TypeConverter typeColor;
typeColor= TypeDescriptor.GetConverter(typeof(Color));
btnsettings .BackColor = (Color)cvColor.ConvertFrom(context, culture,
strValues [0]);
return btnsettings;

and in case ConvertTo you have to convert the value into object.

ButtonAttribute btnsettings =(ButtonAttribute)value;
TypeConverter cvInt;
cvInt = TypeDescriptor.GetConverter(typeof(int));
TypeConverter cvColor;
cvColor = TypeDescriptor.GetConverter(typeof(Color));
// Create the string
string[] parts = new string[NumOfMembers];
parts[0] = (string)cvColor.ConvertTo(settings.BackColor, typeof(string));
parts[1] = (string)cvColor.ConvertTo(settings.ForeColor, typeof(string));
return String.Join(culture.TextInfo.ListSeparator, parts);

return base.ConvertTo(context, culture, value, destinationType);