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

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

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

var result = ColorConverter.ConvertFromString("Red") as Color;

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.

Tags:

Wpf