How do I convert a string like "Red" to a System.Windows.Media.Color?
Solution 1:
var color = (Color)ColorConverter.ConvertFromString("Red");
Solution 2:
System.Windows.Media.ColorConverter is how the XamlReader does it.
var result = ColorConverter.ConvertFromString("Red") as Color;
Solution 3:
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.