Jonas Stawski
Jonas Stawski

Reputation: 6752

System.Windows.Media.Color to color name

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).

Upvotes: 1

Views: 8053

Answers (2)

Handcraftsman
Handcraftsman

Reputation: 6993

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.

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245479

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.

Upvotes: 8

Related Questions