C# WPF Tutorial - Using MultiBindings [Intermediate]


If you've touched WPF at all, you've probably realized that bindings are an extremely important piece of the framework. We've talked about WPF bindings a number of times (most recently in a post where we talked about BindingConverters) - and yet we have just barely scratched the surface in the world of bindings. Today, we are going to take a look at MultiBindings.

What is a MultiBinding? It is a binding that enables you to bind to multiple items and return a single new value using a converter. This is extremely useful if a control in your interface needs to be affected by a number of backend property changes - for instance, any sort of aggregator. Below is a screenshot of the example we are going to build today - and as you can see, we will be doing some aggregating. We will be using a MultiBinding to sum the values of the three sliders and report the total.

MultiBinding Example Screenshot

OK, so let's take a look at the basic XAML to create that interface:
<Window x:Class="MultiBindingExample.MBEWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MultiBindingExample"
    Title="MultiBinding Example" Height="300" Width="300">
  <StackPanel>
    <Slider Margin="5" Value="25" Name="FirstSlider" Maximum="100" 
        Minimum="0" TickFrequency="0.01" IsSnapToTickEnabled="True" />
    <Slider Margin="5" Value="50" Name="SecondSlider" Maximum="100" 
        Minimum="0" TickFrequency="0.01" IsSnapToTickEnabled="True" />
    <Slider Margin="5" Value="75" Name="ThirdSlider" Maximum="100" 
        Minimum="0" TickFrequency="0.01" IsSnapToTickEnabled="True" />

    <Grid HorizontalAlignment="Center">
      <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
      </Grid.RowDefinitions>
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" MinWidth="50" />
      </Grid.ColumnDefinitions>

      <TextBlock Grid.Row="0" Grid.Column="0" Padding="5" TextAlignment="Right">
        First Slider Value:
      </TextBlock>
      <TextBlock Grid.Row="0" Grid.Column="1" Padding="5"
          Text="{Binding ElementName=FirstSlider, Path=Value}" />
      <TextBlock Grid.Row="1" Grid.Column="0" Padding="5" TextAlignment="Right">
        Second Slider Value:
      </TextBlock>
      <TextBlock Grid.Row="1" Grid.Column="1" Padding="5"
          Text="{Binding ElementName=SecondSlider, Path=Value}" />
      <TextBlock Grid.Row="2" Grid.Column="0" Padding="5" TextAlignment="Right">
        Third Slider Value:
      </TextBlock>
      <TextBlock Grid.Row="2" Grid.Column="1" Padding="5"
          Text="{Binding ElementName=ThirdSlider, Path=Value}" />
      <TextBlock Grid.Row="3" Grid.Column="0" Padding="5" TextAlignment="Right">
        Slider Sum:
      </TextBlock>
      <TextBlock Grid.Row="3" Grid.Column="1" Padding="5">
        <TextBlock.Text>

          <!-- MultiBinding Goes Here -->

        </TextBlock.Text>
      </TextBlock>
    </Grid>
    <TextBlock HorizontalAlignment="Center" Margin="0 15 0 0">
      Slider Average
    </TextBlock>
    <Slider Margin="5" Maximum="100" Minimum="0"
        TickFrequency="0.01" IsSnapToTickEnabled="True">
      <Slider.Value>

        <!-- MultiBinding Goes Here -->

      </Slider.Value>
    </Slider>
  </StackPanel>
</Window>
 
The XAML is pretty standard - a bunch of textblocks and sliders. What we really care about is using the values from the top three sliders to determine the value of the sum text block and the value of the average slider - and that is where the MultiBinding comes in. So let's take a look at the xaml for the sum MultiBinding:
<MultiBinding Converter="{StaticResource sumConverter}">
  <Binding ElementName="FirstSlider" Path="Value" />
  <Binding ElementName="SecondSlider" Path="Value" />
  <Binding ElementName="ThirdSlider" Path="Value" />
</MultiBinding>
 
The xaml for a MultiBinding is pretty simple - inside the tag, you just list a bunch of normal binding tags. So here we are binding to the values of the First, Second, and Third slider. The other key point is the converter. A MultiBinding requires a converter because WPF doesn't know how to combine the individual binding values into a single value. So we have to supply some code fore that, and in this case it is the sumConverter. To get that sumConverter static resource, we have to make a static resource in the window resources:
<local:SumConverter x:Key="sumConverter" />
 
And, of course, that line is creating an instance of the SumConverter class, which looks like this:
public class SumConverter : IMultiValueConverter
{
  public object Convert(object[] values, Type targetType, object parameter, 
      System.Globalization.CultureInfo culture)
  {
    double total = 0;
    foreach (double val in values)
      total += val;
    return total.ToString();
  }

  public object[] ConvertBack(object value, Type[] targetTypes, object parameter, 
      System.Globalization.CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}
 
For MultiValue converters, you have to create a class that implements IMultiValueConverter. The difference between this and the standard IValueConverter is that instead of a single value passed in for the Convert function (and a single value passed back for ConvertBack), we get an array. So here in the Convert function, we just sum everything getting passed in and return the result. The ConvertBack function is not implemented, mostly because we don't need it for this simple app.

So let's throw that xaml that we just wrote into the full xaml for the window (and we will add the xaml for the MultiBinding for the average slider):
<Window x:Class="MultiBindingExample.MBEWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MultiBindingExample"
    Title="MultiBinding Example" Height="300" Width="300">
  <StackPanel>
    <Slider Margin="5" Value="25" Name="FirstSlider" Maximum="100" 
        Minimum="0" TickFrequency="0.01" IsSnapToTickEnabled="True" />
    <Slider Margin="5" Value="50" Name="SecondSlider" Maximum="100" 
        Minimum="0" TickFrequency="0.01" IsSnapToTickEnabled="True" />
    <Slider Margin="5" Value="75" Name="ThirdSlider" Maximum="100" 
        Minimum="0" TickFrequency="0.01" IsSnapToTickEnabled="True" />

    <Grid HorizontalAlignment="Center">
      <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
      </Grid.RowDefinitions>
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" MinWidth="50" />
      </Grid.ColumnDefinitions>

      <TextBlock Grid.Row="0" Grid.Column="0" Padding="5" TextAlignment="Right">
        First Slider Value:
      </TextBlock>
      <TextBlock Grid.Row="0" Grid.Column="1" Padding="5"
          Text="{Binding ElementName=FirstSlider, Path=Value}" />
      <TextBlock Grid.Row="1" Grid.Column="0" Padding="5" TextAlignment="Right">
        Second Slider Value:
      </TextBlock>
      <TextBlock Grid.Row="1" Grid.Column="1" Padding="5"
          Text="{Binding ElementName=SecondSlider, Path=Value}" />
      <TextBlock Grid.Row="2" Grid.Column="0" Padding="5" TextAlignment="Right">
        Third Slider Value:
      </TextBlock>
      <TextBlock Grid.Row="2" Grid.Column="1" Padding="5"
          Text="{Binding ElementName=ThirdSlider, Path=Value}" />
      <TextBlock Grid.Row="3" Grid.Column="0" Padding="5" TextAlignment="Right">
        Slider Sum:
      </TextBlock>
      <TextBlock Grid.Row="3" Grid.Column="1" Padding="5">
        <TextBlock.Text>
          <MultiBinding Converter="{StaticResource sumConverter}">
            <Binding ElementName="FirstSlider" Path="Value" />
            <Binding ElementName="SecondSlider" Path="Value" />
            <Binding ElementName="ThirdSlider" Path="Value" />
          </MultiBinding>
        </TextBlock.Text>
      </TextBlock>
    </Grid>
    <TextBlock HorizontalAlignment="Center" Margin="0 15 0 0">
      Slider Average
    </TextBlock>
    <Slider Margin="5" Maximum="100" Minimum="0"
        TickFrequency="0.01" IsSnapToTickEnabled="True">
      <Slider.Value>
        <MultiBinding Converter="{StaticResource avgConverter}">
          <Binding ElementName="FirstSlider" Path="Value" />
          <Binding ElementName="SecondSlider" Path="Value" />
          <Binding ElementName="ThirdSlider" Path="Value" />
        </MultiBinding>
      </Slider.Value>
    </Slider>
  </StackPanel>
</Window>
 
So we have almost all the code now, except for the AvgConverter, which is a little different from the SumConverter. This because here we actually use the ConvertBack method:
public class AvgConverter : IMultiValueConverter
{
  public object Convert(object[] values, Type targetType, object parameter, 
      System.Globalization.CultureInfo culture)
  {
    return values.Average(v => (double)v);
  }

  public object[] ConvertBack(object value, Type[] targetTypes, object parameter, 
      System.Globalization.CultureInfo culture)
  {
    return Array.ConvertAll<Type, Object>(targetTypes, t => value);
  }
}
 
So the Convert function does a simple average (using the Linq extension Average method). In ConvertBack, however, we are passed the value to convert back and an array of types. These types represent the types expected in the object array that we need to return. In this case we know that the value being passed in is a double, and the values expected back are also doubles, so the type array is only useful for the length of the array that we need to return. We do a simplistic convert back for average - we just return an array where every entry is set to the average. This means that if you grab the average slider and move it, all three top sliders will be set to the position of the average slider.

Well, that is it for this intro to MultiBindings in WPF. You can grab the Visual Studio project for this sample app here if you would like to play around with it. 

Source Files:

Comments