Jul 21

Written by: Soul Solutions
Tuesday, 21 July 2009 

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: ,,

Tags:

2 comment(s) so far...

Re: Using Hex Colour values to set Foreground in WPF

Thanks, that's the syntax I was looking for.

By Shirley on   Wednesday, 27 January 2010

Re: Using Hex Colour values to set Foreground in WPF

This is exactly what I was looking for. I had an idea that some type of conversion was needed but not sure what it was ;)

By Bpimenta on   Wednesday, 19 October 2011

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment   Cancel 
Copyright © 2002-2009 Soul Solutions Pty Ltd. | Login