BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Data Binding - Value Converters

The ninety-seventh part of the Windows Presentation Foundation Fundamentals tutorial continues to consider data binding. This article shows how value converters can be used to bind otherwise incompatible data types.

Data Binding

In recent articles in the WPF tutorial we've looked at data binding. Initially we considered basic binding of raw values between controls and data objects. In the previous article I explained how string formatting could be used when converting numeric, date and time and other source values into strings.

Although these data binding techniques are very useful, they do not allow for situations where the data types of the source and destination values are incompatible. WPF will perform some conversion automatically, such as showing numeric values in a text box, despite the Text property using a string. However, most conversions are not automatic and require the use of a value converter.

Value Converters

A value converter is a .NET class that controls the conversion of data between two types. Value converters generally perform bi-directional conversion through two methods, "Convert" and "ConvertBack", although if they are exclusively used in read-only or write-only scenarios, one of these methods may not be implemented. When required, the value converter is linked to a data binding. If the source value changes, the converter generates a value of the correct type and applies it to the target property. Similarly, if the user updates a control's data bound property, the converter changes the entered value to one of the underlying type before writing it back to the source.

In this article we'll see how to add a predefined value converter to a data binding. In the next article we'll create our own value converter. To demonstrate the techniques involved we need a sample solution. Create a new WPF application in Visual Studio, naming the project, "ValueConverterDemo". Once prepared, replace the XAML of the main window with the following code:

<Window x:Class="ValueConverterDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Value Converter Demo"
        Height="200"
        Width="200">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <CheckBox Name="MyCheckBox" Margin="5">Show Ellipse</CheckBox>
        <Ellipse Grid.Row="1" Fill="Red" Stroke="Black" Margin="5"/>
    </Grid>
</Window>

The window layout is quite simple, showing only a CheckBox and an Ellipse. We'll use data binding to link the IsChecked property of the check box to the Visibility property of the ellipse, so that clicking the check box shows or hides the shape. You might imagine that this could be achieved with a simple data binding on the Ellipse, as shown below:

<Ellipse Grid.Row="1" Fill="Red" Stroke="Black" Margin="5"
           Visibility="{Binding ElementName=MyCheckBox,Path=IsChecked}"/>

Make the above change and run the program. You'll find that the ellipse is not affected by changes to the check box. The problem here is that the IsChecked property is Boolean. This is incompatible with the Visibility property, which uses a Visibility value. We need a converter to switch between the two types. Handily, Microsoft has created the BooleanToVisibility converter class. This converts between the two types, mapping true to Visibility.Visible and false to Visibility.Collapsed.

Adding a Converter

There are three steps required in order to use a value converter in a XAML data binding. Firstly, you must ensure that the namespace containing the converter is known. Next, you add the converter as a resource. Finally, the resource can be referenced in the data binding.

The BooleanToVisibilityConverter class is found in the System.Windows.Controls namespace. This makes the demonstration simpler because the namespace is already recognised by the window. No further action is required to register it.

We'll look at resources in detail later in the tutorial. For now, all we need to know is that resources can be added to a window using property element syntax and the Resources property. Each resource is added within the Resources element, defining the type to be used and a unique key for the resource. The key is to identify the resource, and therefore the value converter, within data bindings.

Add the following XAML just above the Grid element, after the closing angle bracket of the initial Window tag. This creates a BooleanToVisibilityConverter resource with the key, "MyConverter".

<Window.Resources>
    <BooleanToVisibilityConverter x:Key="MyConverter"/>
</Window.Resources>

We can now use the converter within data bindings. To add it to a binding you use the Converter parameter, which is set to the correct resource. Update the data binding for the Visibility property of the ellipse, as follows:

<Ellipse Grid.Row="1" Fill="Red" Stroke="Black" Margin="5"
            Visibility="{Binding ElementName=MyCheckBox,Path=IsChecked,
                                Converter={StaticResource MyConverter}}"/>

NB: The StaticResource syntax is used to identify the resource. This will be described later in the tutorial.

Run the program again to see the results. Initially the check box is unchecked and the ellipse is not visible. Clicking the check box causes the ellipse to appear and disappear.

19 September 2014