Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string into a Color? For windows phone c#

I have a user control where I have bounded a string to the xaml path. This makes it possible for me to choose colors like "Black" "Blue" and also use hexa numbers as a string to choose the color.

But I am not able to use the same string in the C# code. Which is shown in the example below:

SolidColorBrush blackBrush = new SolidColorBrush();
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = shieldGearModelRec.Gear.Color;

So the last string shieldGearModelRec.Gear.Color is what I use as a binding in XAML. And it can convert strings to color either in color names or hexa description. But how can I do this in the code behind, that is in c#?

My searches found stuff like Convert string to Color in C# but this was not possible in windows phone. Is there anyway to accomplish this?

An Idea

Do I need to create a converter that reads the string, looks for # to determine if it is hexa or a color name and then using a hexa converter to find rgb, and a switch for the names? This does not seem like the smartest solution

like image 841
JTIM Avatar asked Oct 20 '22 01:10

JTIM


1 Answers

One clever way I saw on net to accomplish this is by creating a string that represent XAML markup for <Color> then use XamlReader to convert the XAML string into actual Color object :

private static bool StringToColor(string strColor, out Color color)
{
    string xaml = string.Format("<Color xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">{0}</Color>", strColor);
    try
    {
        object obj = XamlReader.Load(xaml);
        if (obj != null && obj is Color)
        {
            color = (Color)obj;
            return true;
        }
    }
    catch (Exception)
    {
        //Swallow useless exception
    }
    color = new Color();
    return false;
}

Example of usage :

Color newColor = new Color(); 
StringToColor(shieldGearModelRec.Gear.Color,out newColor); 
mySolidColorBrush.Color = newColor;

Note: Source of StringToColor() method can be found in George's comment to this blog post : Jim McCurdy's Tech Blog - ColorFromString for Silverlight or .NET

like image 84
har07 Avatar answered Oct 27 '22 14:10

har07