如何将字符串转换成颜色? Windows Phone的C# [英] How to convert a string into a Color? For windows phone c#

查看:192
本文介绍了如何将字符串转换成颜色? Windows Phone的C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在那里我已经围成的字符串到XAML路径的用户控件。这样就可以让我选择的颜色一样,黑,蓝,也可以使用六数字作为一个字符串来选择颜色。

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.

但我不能够使用相同字符串中的C#代码。这是在下面的示例所示:

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;



所以,最后一个字符串 shieldGearModelRec.Gear.Color 是我在XAML绑定使用。它可以将字符串转换为彩色无论是在颜色名称或六描述。但我怎么能做到这一点在后面的代码,也就是在C#

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#?

我的搜索找到的东西一样
字符串转换为颜色在C#中,但这是不可能的Windows Phone中。反正有没有做到这一点?

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?

构想

我需要创建一个转换器,读取字符串,查找#以确定它是否是六或颜色名称,然后用六变换器找到RGB,并为名称的开关?这似乎不是最聪明的解决方案。

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

推荐答案

一个聪明的办法,我在网上看到了实现这一目标是通过创建代表一个字符串XAML标记为<颜色> 然后用 XamlReader 来的XAML字符串转换为实际的颜色目标:

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;

请注意:来源StringToColor()方法在乔治的评论可以发现这个博客帖子:吉姆·麦柯迪的技术博客 - ColorFromString Silverlight的或.NET

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

这篇关于如何将字符串转换成颜色? Windows Phone的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆