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

心已入冬 提交于 2019-12-22 08:27:54

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/25827964/how-to-convert-a-string-into-a-color-for-windows-phone-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!