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# Snippet - The Many Uses Of The Using Keyword [Beginner]

What is the first thing that pops into your mind when you think of the using keyword for C#? Probably those lines that always appear at the top of C# code files - the lines that import types from other namespaces into your code. But while that is the most common use of the using keyword, it is not the only one. Today we are going to take a look at the different uses of the using keyword and what they are useful for. The Using Directive There are two main categories of use for the using keyword - as a "Using Directive" and as a "Using Statement". The lines at the top of a C# file are directives, but that is not the only place they can go. They can also go inside of a namespace block, but they have to be before any other elements declared in the namespace (i.e., you can't add a using statement after a class declaration). Namespace Importing This is by far the most common use of the keyword - it is rare that you see a C# file that does not h

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