C# WPF - Convert colour to brush for UI styling

Something that may be occasionally frustrating is trying to quickly colour a UI element on a WPF window programmatically when you know the colour code, or maybe even have a 'color' variable storing the colour for you. There can be various ways to do this depending on how you have your colour stored, so this post gives a couple of ways to convert a colour into a brush to style a UI element.

Converting from String

Converting a colour to a string can be done using a brush converter. It's best if the string represents a colour code in a 6-digit hexadecimal format ("#FF0000" for example). Other variations may work but I've only tried and tested the one I'm about to show.

There are other ways to convert colours to brushes using the brush converter, including from objects, mostly inherited from TypeConverter. For a full list of methods available to the brush converter, see the MSDN article here.

Converting from System.Windows.Media.Color

Converting from a system colour can be done by an instantiation of the SolidColorBrush type and feeding it the colour as a parameter in the constructor, like so:

Alternatively, if you have the colour stored in a variable then you can convert it like this:

Conclusion

These methods provide two ways to convert a colour into a brush that you can then use to fill a rectangle or other UI element as necessary using programmatic means. I posted this because in the last few months I have had to do this a bit, and kept forgetting how each time I wanted to, so hopefully this will serve as a useful reminder.

Leave a Reply

Your email address will not be published. Required fields are marked *