简体   繁体   中英

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 (ie output "Rojo" for spanish).

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM