Best solution for XmlSerializer and System.Drawing.Color

System.Drawing.Color objects apparently won't serialize with XmlSerializer. What is the best way to xml serialize colors?


Solution 1:

The simplest method uses this at it's heart:

String HtmlColor = System.Drawing.ColorTranslator.ToHtml(MyColorInstance);

It will just convert whatever the color is to the standard hex string used by HTML which is just as easily deserialized using:

Color MyColor = System.Drawing.ColorTranslator.FromHtml(MyColorString);

That way you're just working with bog standard strings...

Solution 2:

Final working version:

Color clrGrid = Color.FromArgb(0, 0, 0);
[XmlIgnore]
public Color ClrGrid 
{
    get { return clrGrid; }
    set { clrGrid = value; }
}
[XmlElement("ClrGrid")]
public string ClrGridHtml
{
    get { return ColorTranslator.ToHtml(clrGrid); }
    set { ClrGrid = ColorTranslator.FromHtml(value); }
}

Solution 3:

We use this:

[Serializable]
public struct ColorEx
{
    private Color m_color;

    public ColorEx(Color color)
    {
        m_color = color;
    }

    [XmlIgnore]
    public Color Color
    { get { return m_color; } set { m_color = value; } }

    [XmlAttribute]
    public string ColorHtml
    { 
        get { return ColorTranslator.ToHtml(this.Color); } 
        set { this.Color = ColorTranslator.FromHtml(value); } }

    public static implicit operator Color(ColorEx colorEx)
    {
        return colorEx.Color;
    }

    public static implicit operator ColorEx(Color color)
    {
        return new ColorEx(color);
    }
}

Solution 4:

You could write a simple wrapper class for Color that exposes the ARGB values as properties. You could translate to/from the colors using from/to ARGB conversions (see docs). Something like:

[Serializable] 
public class ColorWrapper
{
   private Color color;

   public ColorWrapper (Color color)
   {  
      this.color = color;
   }

   public ColorWrapper()
   {
    // default constructor for serialization
   }

   public int Argb
   { 
       get
       {
           return color.ToARGB(); 
       }
       set 
       {
           color = Color.FromARGB();
       }
   }
}

Probably want an accessor for the color too!

Benefit of this is that the class can be used in all places you have to serialize colors. If you want to make the XML readable (rather than an arbitrary ARGB integer) you could use the to/from HTML methods as described by balabaster.