20

How I can cast color name to SolidColorBrush type? I mean the word i.e. "Yellow".

SolidColorBrush scb =  ??? ; // "Yellow" 

Thank you!

NoWar
  • 36,338
  • 80
  • 323
  • 498
  • 2
    I would simply [_construct_](http://msdn.microsoft.com/en-us/library/ms558629.aspx) a `SolidColorBrush` from a `Color`. – Uwe Keim Feb 14 '12 at 12:25

4 Answers4

42

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

Brush brush=new SolidColorBrush(Colors.Red);
HCL
  • 36,053
  • 27
  • 163
  • 213
  • This is perfect in WPF, but not working in Windows Phone 8, how to do this in WP8 – Zia Ur Rahman Nov 11 '15 at 09:11
  • Maybe this helps: http://stackoverflow.com/questions/25827964/how-to-convert-a-string-into-a-color-for-windows-phone-c-sharp – HCL Nov 11 '15 at 09:28
14

If you already know the name of the color you can get the brush directly from Brushes:

SolidColorBrush scb = Brushes.Yellow; //scb seems a bit redundant at this point...

In code you should usually not use converters unless you have a string whose value you do not know.

H.B.
  • 166,899
  • 29
  • 327
  • 400
8

You cannot cast one 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 SolidColorBrush with a specific color, for example:

 var brush = new SolidColorBrush(Color.Yellow);
Christian.K
  • 47,778
  • 10
  • 99
  • 143
5
// Yellow is green + red
SolidColorBrush yellowBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 0));
ken2k
  • 48,145
  • 10
  • 116
  • 176