views:

50

answers:

2

I have the following:

Color color = Colors.Red;
color.ToString();

which outputs as the hexadecimal representation. Is there any way to output "Red"?

Bonus points to whoever gives a solutions that works with different cultures (i.e. output "Rojo" for spanish).

Thanks in advanced...

+3  A: 

It looks like you might have to hand-roll your own solution using Reflection. Here's my first shot:

public static string GetColorName(this System.Windows.Media.Color color)
{
    Type colors = typeof(System.Windows.Media.Colors);
    foreach(var prop in colors.GetProperties())
    {
        if(((System.Windows.Media.Color)prop.GetValue(null, null)) == color)
            return prop.Name;
    }

    throw new Exception("The provided Color is not named.");
}

Keep in mind that this is by no means efficient, but from what I can see in the documentation it would be the only way.

Justin Niessner
This is for Windows Phone 7 so I wonder if this code would pass certification
Jonas Stawski
A: 

One option might be to convert the Media.Color to a Drawing.Color

private System.Drawing.Color ColorFromMediaColor(System.Windows.Media.Color clr)
{
  return System.Drawing.Color.FromArgb(clr.A, clr.R, clr.G, clr.B);
}

Then use the Name property from the Drawing.Color object to get the color name.

As for localizing, you could look up the color name in a translation dictionary built from resource files you provide.

Handcraftsman
This will certainly not work because color.name will not look up for every color you create.
Akash Kava
The question asked for the color name for built-in color objects e.g. Color.Red, not arbitrary ones created by the user, so it should work.
Handcraftsman
Sorry, it doesn't work because System.Drawing is not part of the Silverlight CLR
Jonas Stawski