Introduction

A co-worker came to me the other day and asked how she could enable a TextBox when a particular radio button was not selected in WPF. The problem she noted was that she couldn't directly bind the Textbox.IsEnabled property to the RadioButton.IsChecked property. What she really wanted to do was bind IsEnabled to !IsChecked. This article provides an introduction to value converters in WPF using a simple and practical example of a BoolToOppositeBool converter.

Sample Project

The sample scenario for this article is a WPF Windows application with three radio buttons and a TextBox. When the Red radio button is selected, we want the TextBox to be disabled. When any other radio button is selected, we want the TextBox to be enabled. The OppositeBoolConverter discussed in this article is used so that we can leverage data binding.

What are Value Converters?

As the name implies, a value converter converts one type to another. Converters are frequently used in data binding scenarios where the target type and the source type are not the same. Value converters are used heavily in WPF because XAML attributes are strings, but these strings often need to be converted into objects. For instance, the stringvalue of red for a background in XAML needs to be converted to a Color object representing red.

Creating a Custom Converter

To create a custom converter, simply create a class implementing the System.Windows.Data.IValueConverter interface. This interface defines two methods:

If you are only using one-way databinding, you only need to implement the Convert method, which is what I have done. In the case of the BoolToOppositeBoolConverter, the Convert implementation returns the opposite boolean valueof what was passed in.

Using the Converter

Once you have created a custom converter, the next step is to leverage that in data binding by adding the Converter property to a binding expression and specifying an instance of the Converter. In order to implement the scenario of binding a TextBox's IsEnabled property to a radio button's IsChecked property, I first imported the namespaceof my Converter into the XAML file:

xmlns:wpfdude="clr-namespace:OppositeValueConverterDemo.Converters"

Next, I created an instance of the Converter as a resource of the Window, with a key of oppositeConverter:

Summary

The data binding features of WPF minimize the need to write code and value converters extend the scenarios where data binding can be applied. Implementing your own custom value converters can sound intimidating. I hope this article showed that creating one isn't something you need to shy away from.