views:

68

answers:

1

Basically i have a settings class like this:

class Settings
{
  Color BackgroundColor {get;set;}
  Color ForegroundColor {get;set;}
  Color GridColor {get;set;}
  Color HighlightColor {get;set;}
  //... etc

}

And i want to be able to do both - serialize the settings class and edit the colors in propertygrid.

The solution I've come up so far is this:

class Settings
{
  [XmlIgnore]
  Color BackgroundColor {get;set;}

  [Browsable(false)]
  [XmlElement("BackgroundColor")]
  public string HtmlBackgroundColor
  {
    get
    {
      return ColorTranslator.ToHtml(BackgroundColor);
    }
    set
    {
      Color = ColorTranslator.FromHtml(value);
    }
  }
 // etc            
}

But this approach sucks because I've to write a lot of code for each color.

The preferred solution should look something like this:

class Settings
{
  SColor BackgroundColor {get;set;}
  SColor ForegroundColor {get;set;}
  SColor GridColor {get;set;}
  SColor HighlightColor {get;set;}
  // etc
}

Where SColor is editable in propertygrid exactly like the System.Drawing.Color, but at the same time is serializable.

How could I achieve this?

A: 

You should be able to make the properties of your custom type visible in the PropertyGrid by applying a type converter via an attribute:

[TypeConverter(typeof(ExpandableObjectConverter)]
public class SColor
{ 
  // public properties that you wish serialized and displayed in the property grid
} 

Essentially, a TypeConverter is a class that informs various components in the .NET Framework about how to convert between types, and do other things involving those types, such as create new instances or retrieve their properties. ExpandableObjectConverter is a built-in TypeConverter that simply reflects against a type to get its properties for display in the PropertyGrid.

My example will work as long as you are editing a property of type SColor that has an instance assigned to it, so make sure to initialize these properties in the constructor for the Settings class. If you actually want to be able to create a new SColor instance from the PropertyGrid on a property that has a null value, then you will need to derive your own TypeConverter class.

luksan
Did you read the question? SColor won't be editable in propertygrid just like the System.Drawing.Color is. SColor has to be edited using ColorEditor.
JBeurer
My impression from the question was that you wanted to be able to edit the properties of SColor in the PropertyGrid... ColorEditor is not even mentioned in your original post.
luksan
But I DID mention that SColor should be editable in propertygrid just like the System.Drawing.Color. The only difference between SColor and System.Drawing.Color is that SColor should be xml serializable.
JBeurer