Using Hex Colour values to set Foreground in WPF

I needed to assign a foreground colour to an item in code-behind and all i had was the HEX value of the colour. My first instinct was to set the foreground directly from the string e.g.

textRichTextBoxEditor.Foreground = "#FF97315A";

but Foreground takes a Brush so I then thought about casting the string to a Brush e.g.

textRichTextBoxEditor.Foreground = (Brush)"#FF97315A";

But that doesn’t work and creating a new Brush takes no parameters. So I thought maybe create a SolidColorBrush and give it my colour e.g.

textRichTextBoxEditor.Foreground = new SolidColorBrush("#FF97315A")

But it takes a Color, not a string. So I needed to convert from a hex string to a Brush. Enter the BrushConverter. The solution ended up being:

var bc = new BrushConverter();
textRichTextBoxEditor.Foreground = (Brush)bc.ConvertFrom("#FF97315A");;

 

Technorati Tags: ,,