Best solution for XmlSerializer and System.Drawing.Color

十年热恋 提交于 2019-12-17 09:40:29

问题


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


回答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...




回答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); }
}



回答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);
    }
}



回答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.



来源:https://stackoverflow.com/questions/376234/best-solution-for-xmlserializer-and-system-drawing-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!