Skip to main content

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

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >(); ...

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as...

C# WPF Tutorial - Implementing IScrollInfo [Advanced]

The ScrollViewer in WPF is pretty handy (and quite flexible) - especially when compared to what you had to work with in WinForms ( ScrollableControl ). 98% of the time, I can make the ScrollViewer do what I need it to for the given situation. Those other 2 percent, though, can get kind of hairy. Fortunately, WPF provides the IScrollInfo interface - which is what we will be talking about today. So what is IScrollInfo ? Well, it is a way to take over the logic behind scrolling, while still maintaining the look and feel of the standard ScrollViewer . Now, first off, why in the world would we want to do that? To answer that question, I'm going to take a an example from a tutorial that is over a year old now - Creating a Custom Panel Control . In that tutorial, we created our own custom WPF panel (that animated!). One of the issues with that panel though (and the WPF WrapPanel in general) is that you have to disable the horizontal scrollbar if you put the panel in a ScrollV...