How to convert string to SolidColorBrush in C#?

11.1k Views Asked by At

I'm trying to convert a string to a SolidColorBrush in C#. The code I'm using is:

arrColors[arrColors.Length - 1] = 
                         (SolidColorBrush)new BrushConverter().ConvertFromString(sLine);

where sLine is a string read from a text file. For example, sLine might be "Black".

This code gives me a FormatException.

2

There are 2 best solutions below

15
On

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 SolidColorBrush from that colour, like so:

SolidColorBrush brush = new SolidColorBrush(color);

EDIT: If the string being converted is English but the current culture is not, you may need to use ConvertFromInvariantString instead, like so:

ColorConverter converter = new ColorConverter();
Color color = (Color)converter.ConvertFromInvariantString(sLine);
0
On

Try this:

var color = (Color)ColorConverter.ConvertFromString(sLine);
var brush = new SolidColorBrush(color);