willem
willem

Reputation: 27027

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

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?

Upvotes: 49

Views: 45945

Answers (6)

E_A
E_A

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

Tom Smykowski
Tom Smykowski

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

kirie
kirie

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

Kent Boogaart
Kent Boogaart

Reputation: 178780

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

Upvotes: 115

user1228
user1228

Reputation:

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

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

Upvotes: 16

Jon Skeet
Jon Skeet

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

Related Questions