Steve Chadbourne
Steve Chadbourne

Reputation: 6953

Windows Phone string to color

There is no System.Windows.Media.ColorConverter in Windows Phone (or Silverlight) so I need another way to take a string containing a color name e.g. "Red" and generate a Color object from it.

I found this possibility but it doesn't work as colorType.GetProperty always returns null.

public static Color ConvertFromString(string colorString)
{
    Color retval = Colors.Transparent;

    Type colorType = (typeof(Colors));

    if (colorType.GetProperty(colorString) != null)
    {
        object o = colorType.InvokeMember(colorString,
            BindingFlags.GetProperty, null, null, null); 

        if (o != null)
        {
            retval =  (Color)o;
        }
    }

    return retval;
}

Any ideas?

Upvotes: 1

Views: 610

Answers (2)

StaWho
StaWho

Reputation: 2488

Not tried it on WP, but in SL you can hijack XAML for this (and also for SolidColorBrush and such):

    private Color StringToColor(string colorName)
    {
        string xaml = string.Format("<Color xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">{0}</Color>", colorName);
        try { return (Color)XamlReader.Load(xaml); }
        catch { return Colors.Transparent; }
    }

Upvotes: 2

Tanuj Wadhwa
Tanuj Wadhwa

Reputation: 2045

Try this :

public static Color GetColor(String ColorName)
{
    Type colors = typeof(System.Windows.Media.Colors);
    foreach(var prop in colors.GetProperties())
    {
        if(prop.Name == ColorName)
            return ((System.Windows.Media.Color)prop.GetValue(null, null));
    }

    throw new Exception("No color found");
}

Upvotes: 2

Related Questions