C# 将颜色名称投射到 SolidColorBrush
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9276813/
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
Cast Color Name to SolidColorBrush
提问by Developer
How I can castcolor nameto SolidColorBrushtype? I mean the word i.e. "Yellow".
我如何投射颜色名称来SolidColorBrush输入?我的意思是“黄色”这个词。
SolidColorBrush scb = ??? ; // "Yellow"
Thank you!
谢谢!
采纳答案by HCL
For getting the color, use:
要获取颜色,请使用:
Color col=(Color)ColorConverter.ConvertFromString("Red");
Then create your brush:
然后创建你的画笔:
Brush brush=new SolidColorBrush(col);
or if you can use the Colors-enum
或者如果您可以使用 Colors-enum
Brush brush=new SolidColorBrush(Colors.Red);
回答by ken2k
// Yellow is green + red
SolidColorBrush yellowBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 0));
回答by Christian.K
You cannot castone to another. They are simply different concepts. A brush is brush and color is, well, a color. Just because a brush "paints" in a specific color, doesn't mean you can interchange one with another.
你不能将一个投射到另一个。它们只是不同的概念。画笔就是画笔,颜色就是一种颜色。仅仅因为刷子以特定颜色“绘画”,并不意味着您可以将一种颜色与另一种颜色互换。
You can however create a SolidColorBrushwith a specific color, for example:
但是,您可以创建具有特定颜色的SolidColorBrush,例如:
var brush = new SolidColorBrush(Color.Yellow);
回答by H.B.
If you already know the name of the color you can get the brush directly from Brushes:
如果您已经知道颜色的名称,则可以直接从Brushes以下位置获取画笔:
SolidColorBrush scb = Brushes.Yellow; //scb seems a bit redundant at this point...
In code you should usually notuse converters unless you have a string whose value you do not know.
在代码中,您通常不应该使用转换器,除非您有一个您不知道其值的字符串。

