How do I serialize a System.Windows.Media.Color object to an sRGB string? How do I serialize a System.Windows.Media.Color object to an sRGB string? wpf wpf

How do I serialize a System.Windows.Media.Color object to an sRGB string?


If you create your colors using either Color.FromRgb or Color.FromArgb instead of FromScRgb you should get a hex string result from ToString.

If you want to do it manually

string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", c.A, c.R, c.G, c.B);

You can use int.Parse(,NumberStyles.HexNumber) to go the other way.

Note sRGB and scRGB refer to different color spaces, make sure your using the one you want.


You can also do it this way:

string myHex = new ColorConverter().ConvertToString(myColor);


I created a struct to handle conversion and serialisation. It solves two problems for me: it is serialisable and it corrects the spelling ;)

[Serializable]public struct Colour    {    public byte A;    public byte R;    public byte G;    public byte B;    public Colour(byte a, byte r, byte g, byte b)        {        A = a;        R = r;        G = g;        B = b;        }    public Colour(Color color)        : this(color.A, color.R, color.G, color.B)        {        }    public static implicit operator Colour(Color color)        {        return new Colour(color);        }    public static implicit operator Color(Colour colour)        {        return Color.FromArgb(colour.A, colour.R, colour.G, colour.B);        }    }

Just use Colour where you would otherwise use System.Windows.Media.Color