views:

2009

answers:

3

I'm trying to convert from a System.Drawing.Color to a Silverlight System.Windows.Media.Color. I'm actually trying to pass this color through a service.

The System.Drawing.Color, passed over the wire, does not serialize the argb value independently.

I can convert the argb value to a 32-bit int

[DataMember]  
public int MyColor { get { return Color.Red.ToArgb(); } set {} }

But I don't see any corresponding method in System.Windows.Media.Color to convert that back.

What is the best way to do this?

+1  A: 

The 32-bit representation of System.Drawing.Color assumes a set byte-ordering (e.g ARGB) and that each channel is represented by 8-bits.

Silverlight does not make these assumptions. Instead Media.Color is stored as four 32-bit floating point values and the ordering is based on the color profile.

To create a Media.Color value from a System.Drawing.Color you should use the FromArgb / FromRgb methods and pass in the four separate components.

If necessary You could get these components by AND'ing out the components from the combined 32-bit value. You know (or can find out) the order of the bytes in this color value, which is knowledge that Silverlight does not have.

Andrew Grant
A: 

Thanks. That's pretty much what I did, though I had to add the .ToHtml method in order to output it in hex notation:

[DataMember]
public string MyColor { 
    get { 
        return ColorTranslator.ToHtml(  
                   Color.FromArgb(  
                       Color.Red.A, 
                       Color.Red.R, 
                       Color.Red.G, 
                       Color.Red.B  
            )); 
     } 
     private set{}   
}

So that on the other side, I could use the code borrowed from here http://blogs.microsoft.co.il/blogs/alex_golesh/archive/2008/04/29/colorconverter-in-silverlight-2.aspx to convert the hex to a solid brush.

It works but it is ugly and seems rather complicated for what I had assumed, wrongly obviously, would be a single method. Maybe in the next release.

A: 

This is what Microsoft says to do - but I wouldn't recommend it.

 String xamlString = "<Canvas xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" Background=\"MistyRose\"/>";
  Canvas c = (Canvas) System.Windows.Markup.XamlReader.Load(xamlString);
  SolidColorBrush mistyRoseBrush = (SolidColorBrush) c.Background;
  Color mistyRose = mistyRoseBrush.Color;

Thats completely insane if you ask me - but thats from the MS docs!

Simon_Weaver