BooleanToBrushConverterJuly 28, 2012
A common use case in Windows Phone (or generally Silverlight / WPF) development is having to change a UI element’s color (background and/or foreground) depending on a Boolean state in your ViewModel. The most common case for that is possibly an active / inactive state of a ViewModel which should reflect in the user interface.
In fact, I encountered this use case that often, that I decided to cover it in a custom converter class called BooleanToBrushConverter, which implements this functionality. This converter class is intended to be used whenever a Boolean property is data bound to some UI element’s brush. BooleanToBrushConverter exposes two dependency properties TrueBrush and FalseBrush and by providing values for these properties, the Boolean values true and false are mapped to Brush objects in the user interface accordingly. Everything fully declarative in my XAML file without a single line of C# code.
The first code block show the implementation of the converter class.
The next code snippet shows how an instance of this BooleanToBrushConverter is declared in the Resources section of a user interface element. This snippet uses an existing resource for the TrueBrush (i.e. the brush that is mapped to the Boolean true value) and declares a new gray SolidColorBrush for the FalseBrush (i.e. the brush that is mapped to the Boolean false value) to demonstrate both concepts.
The last code snippet shows how to apply this converter class in a Binding for a Border element which will get different background colors depending on the IsAvailable property in its bound ViewModel.