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 - MultiBindings

The one hundred and first part of the Windows Presentation Foundation Fundamentals tutorial continues to look at data binding. This article describes how a single property can be bound to multiple data sources.

Data Binding

The latest articles in the WPF tutorial have concentrated on data binding. So far, the data binding that we've looked at produces a result where a property of a control is linked to a single source value. In the case of priority bindings, several possible bindings can be read but only one is selected at any time.

In some situations, binding to a single value doesn't product the result that you want. Instead, you may want to combine information from several data sources. For example, you might have three numeric properties representing the red, green and blue elements of a colour. To display the colour, you might want to bind the Background property of a control to all three values.

This type of binding is made possible with the MultiBinding class. A MultiBinding includes a series of bindings, each providing part of the value for the destination property. This is coupled with a converter that can transform the individual binding results into the final value.

To demonstrate MultiBindings we'll use a window that includes three Sliders to represent the three elements of a colour. We'll bind a Border control's Background property to the sliders and create a converter class that performs the required translation. To begin, create a new WPF application project in Visual Studio named, "MultiBindingDemo". Once the solution is ready, replace the XAML of the main window with the following code:

<Window x:Class="MultiBindingDemo.MainWindow"
        Title="MultiBinding Demo"

            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="100"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>

        <Label Grid.Row="1">Green</Label>
        <Label Grid.Row="2">Blue</Label>

        <Slider Name="Red" Grid.Column="1" Maximum="255" Value="255"/>
        <Slider Name="Green" Grid.Column="1" Grid.Row="1" Maximum="255" Value="255"/>
        <Slider Name="Blue" Grid.Column="1" Grid.Row="2" Maximum="255" Value="255"/>

        <Border Grid.Column="2" Grid.RowSpan="3"
                BorderBrush="Black" BorderThickness="3"
                CornerRadius="5" Margin="3"/>

The resultant window appears as shown below:

WPF MultiBinding demo window

4 October 2014