wpf 如何在 C# 中将字符串转换为 SolidColorBrush?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27303184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert string to SolidColorBrush in C#?
提问by Niels Bril
I'm trying to convert a stringto a SolidColorBrushin C#. The code I'm using is:
我试图将转换string为SolidColorBrushC#中。我使用的代码是:
arrColors[arrColors.Length - 1] =
(SolidColorBrush)new BrushConverter().ConvertFromString(sLine);
where sLine is a string read from a text file. For example, sLinemight be "Black".
其中 sLine 是从文本文件中读取的字符串。例如,sLine可能是“黑色”。
This code gives me a FormatException.
这段代码给了我一个FormatException.
回答by Tom Galvin
Assuming all of your brushes are solid colours, you could construct a Color from a string as follows:
假设你所有的画笔都是纯色的,你可以从一个字符串构造一个颜色,如下所示:
Color color = (Color)ColorConverter.ConvertFromString(sLine);
Then you could create a SolidColorBrushfrom that colour, like so:
然后你可以SolidColorBrush从那个颜色创建一个,像这样:
SolidColorBrush brush = new SolidColorBrush(color);
EDIT: If the string being converted is English but the current culture is not, you may need to use ConvertFromInvariantStringinstead, like so:
编辑:如果被转换的字符串是英语但当前的文化不是,你可能需要使用ConvertFromInvariantString代替,像这样:
ColorConverter converter = new ColorConverter();
Color color = (Color)converter.ConvertFromInvariantString(sLine);
回答by Pavel Pykhtin
Try this:
尝试这个:
var color = (Color)ColorConverter.ConvertFromString(sLine);
var brush = new SolidColorBrush(color);

