tags:

views:

691

answers:

4

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?

A: 

System.Windows.Media.ColorConverter is how the XamlReader does it.

var result = ColorConverter.ConvertFromString("Red") as Color;
Will
+5  A: 

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.

Jon Skeet
Nice advice, thanks!
willem
+9  A: 
var color = (Color)ColorConverter.ConvertFromString("Red");

HTH, Kent

Kent Boogaart
That's exactly what I was looking for! Plain and simple, thanks!
willem
A: 

This code makes translating name to Color class faster:

public class FastNameToColor { Dictionary Data = new Dictionary();

    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.

tomaszs