If you have a complex member property (a class that isn’t a .NET system type) and you want to display and edit through PropertyGrid, follow these steps:
- Derive from base class
System.ComponentModel.ExpandableObjectConverter
- Add TypeConverter(typeof(yourClass)) attribute on this class
- Optionally Add Description(“your description”) attribute as well. Common descriptions include “Expand to see options” as your property value will not be editable without expanding drop down
- Override ToString for better display of your object ‘state’ in the property grid
- IMPORTANT: provide a default constructor – otherwise it excepts quietly and you are not sure why
Optionally…Override the 4 base class methods for conversion / serialization to string
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture,
object value,
System.Type destinationType)
{
if (destinationType == typeof(System.String) && value is StatusCommand)
{
//Convert / Serialize your object to string (usually in a parsable property bag)
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
StatusCommand statusCommand = new StatusCommand();
if (value is string)
{
try
{
//Parse the string
string s = (string)value;
string[] elements = s.Split(';');
foreach (var elem in elements)
{
string[] fields = elem.Split('=');
switch (fields[0])
{
case "Version":
break;
break;
case "FirmwareVersionMajor":
statusCommand.FirmwareVersionMajor = Convert.ToByte(fields[1]);
break;
case "FirmwareVersionMinor":
statusCommand.FirmwareVersionMinor = Convert.ToByte(fields[1]);
break;
}
}
return statusCommand;
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
throw new ArgumentException(
"Can not convert '" + (string)value +
"' to type SpellingOptions");
}
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertFrom(ITypeDescriptorContext context,
System.Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context,
System.Type destinationType)
{
if (destinationType == typeof(StatusCommand))
return true;
return base.CanConvertTo(context, destinationType);
}