How do I convert a string like "Red" to a System.Windows.Media.Color?

Viewed 40777

I know I can go the long route by...

  1. Adding a reference to System.Drawing
  2. Creating a System.Drawing.Color from the string
  3. Creating the System.Windows.Media.Color from the ARGB values of the System.Drawing.Color.

But this feels like serious overkill.

Is there an easier way?

6 Answers
var color = (Color)ColorConverter.ConvertFromString("Red");

New and better answer

Of course, ColorConverter is the way to go. Call ColorConverter.ConvertFromString and cast the result. Admittedly this will involve boxing. If you want to avoid boxing, build a dictionary up to start with for the standard names (still using ColorConverter) and then use the dictionary for subsequent lookups.

Original answer

You could fairly easily fetch the property names and values from System.Windows.Media.Colors once into a map:

private static readonly Dictionary<string, Color> KnownColors = FetchColors();

public static Color FromName(string name)
{
    return KnownColors[name];
}

private static Dictionary<string, Color> FetchColors()
{
    // This could be simplified with LINQ.
    Dictionary<string, Color> ret = new Dictionary<string, Color>();
    foreach (PropertyInfo property in typeof(Colors).GetProperties())
    {
        ret[property.Name] = (Color) property.GetValue(null);
    }
    return ret;
}

It's a bit ugly, but it's a one-time hit.

This code makes translating name to Color class faster:

public class FastNameToColor
{
    Dictionary<string, Color> Data = new Dictionary<string, Color>();

    public FastNameToColor()
    {
        System.Reflection.PropertyInfo[] lColors = typeof(System.Drawing.Color).GetProperties();

        foreach (PropertyInfo pi in lColors)
        {
            object val = pi.GetValue(null, null);
            if (val is Color)
            {
                Data.Add(pi.Name, (Color)val);
            }
        }
    }

    public Color GetColor(string Name)
    {
        return Data[Name];
    }
}

You can expand this code to translate name to Media.Color directly.

This code makes it easier to Convert Hex string to brush in c#, wpf

var brush = (Brush)new 
System.Windows.Media.BrushConverter().ConvertFromString("#28808080");
Related