Jump to content

WPF - BrushConverter HTML (Hexadecimal) colors

Posted on:January 29, 2011 at 01:00 AM

Assigning HTML like colors (i.e. #318D38) in WPF application directly in XAML is very easy and smooth. For example code:

<Setter Property="Background" Value="#318D38" />

works pretty well. It is worse to assign HTML color in C# code… Solutions like:

panel.Background = "#318D38";

or

panel.Background = (Brush)"#318D38";

does not work… Solution for this issue is

BrushConverter class. With BrushConverter coder can do something like this:

BrushConverter bc = new BrushConverter();
Brush brush = (Brush)bc.ConvertFrom("#318D38");
panel.Background = brush;

or even this:

BrushConverter bc = new BrushConverter();
Brush brush = (Brush)bc.ConvertFrom("Red");
panel.Background = brush;

Small class but helps a lot ;)