Reputation: 27027
I know I can go the long route by...
But this feels like serious overkill.
Is there an easier way?
Upvotes: 49
Views: 45945
Reputation: 131
This code makes it easier to Convert Hex string to brush in c#, wpf
var brush = (Brush)new
System.Windows.Media.BrushConverter().ConvertFromString("#28808080");
Upvotes: 0
Reputation: 26129
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.
Upvotes: 1
Reputation: 342
Fyi, another easier way is just use microsoft built static class, ex Colors.Red
http://msdn.microsoft.com/en-us/library/windows/desktop/bb189018.aspx
Upvotes: 1
Reputation: 178780
var color = (Color)ColorConverter.ConvertFromString("Red");
Upvotes: 115
Reputation:
System.Windows.Media.ColorConverter is how the XamlReader does it.
var result = ColorConverter.ConvertFromString("Red") as Color;
Upvotes: 16
Reputation: 1502985
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.
Upvotes: 14