Simple example of MultiBinding and IMultiValueConverter in MVVM w.r.t WPF

Niladri.Biswas
Posted by in WPF category on for Beginner level | Points: 250 | Views : 40877 red flag
Rating: 3 out of 5  
 1 vote(s)

In this article, we will explore the concept of MultiBinding and IMultiValueConverter with the help of simple example.


 Download source code for Simple example of MultiBinding and IMultiValueConverter in MVVM w.r.t WPF

Introduction

In this article, we will explore the concept of MultiBinding and IMultiValueConverter with the help of simple example.

What is MultiBinding?

It is a kind of binding that allows to bind multiple items and returns a single value.

What is IMultiValueConverter?

It provides a way to apply custom logic in a System.Windows.Data.MultiBinding.It has two methods viz. Convert and ConvertBack.

Straight To Example

Now we will look into a simple example to explore the concept.We will have two textbox controls that will reflect the First Name and Last Name and a third text box control that will reflect the Complete Name.

If the user changes the value in the "First Name" field, it will be reflected in the "Complete Name" field's first name part.If the user does the same for "Last Name" field,it will be reflected in the "Complete Name" field's last name part The reverse should also be true.

Let us write a class file "CustomMultiValueConvertor.cs" that implements "IMultiValueConverter" interface.

using System;
using System.Windows.Data;

namespace WpfApplication1
{
    public class CustomMultiValueConvertor : IMultiValueConverter

    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
           return String.Concat(values[0], " ", values[1]);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {         
            return (value as string).Split(' ');
        }
    }
}

In the "Convert" function, values[0] is the first name while values[1] is the last name.We are concatenating the first and second values and delimiting them with spaces.

In the "ConvertBack" function, we are splitting the values and returning object arrays

The xaml file looks as under

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" 
        Height="337.633" 
        Width="386.484"
        xmlns:local ="clr-namespace:WpfApplication1">
    
<Window.Resources>
    
    <local:CustomMultiValueConvertor x:Key="MyCustomConvertor"></local:CustomMultiValueConvertor>
        
</Window.Resources>
    
    <Grid Margin="0,0,0,157">
        <Label Content="First Name" HorizontalAlignment="Left" VerticalAlignment="Top"/>
        <TextBox x:Name="txtFirstName" HorizontalAlignment="Left" Height="23" Margin="101,3,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="267"/>
        <Label Content="Last Name" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,41,0,0"/>
        <TextBox x:Name="txtLastName" HorizontalAlignment="Left" Height="23" Margin="101,44,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="267"/>
        <Label Content="Complete Name" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,99,0,0"/>
        <TextBox x:Name="txtCompleteName" HorizontalAlignment="Left" Height="23" Margin="101,102,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="267">
            <TextBox.Text>
                
                <MultiBinding Converter="{StaticResource MyCustomConvertor}" UpdateSourceTrigger="PropertyChanged">
                    <Binding ElementName="txtFirstName" Path="Text" />
                    <Binding ElementName="txtLastName" Path="Text" />
                </MultiBinding>

            </TextBox.Text>
        </TextBox>
    </Grid> 
</Window>

The interesting stuff is lying in the below snippet

<TextBox x:Name="txtCompleteName" HorizontalAlignment="Left" Height="23" Margin="101,102,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="267">
            <TextBox.Text>
                
                <MultiBinding Converter="{StaticResource MyCustomConvertor}" UpdateSourceTrigger="PropertyChanged">
                    <Binding ElementName="txtFirstName" Path="Text" />
                    <Binding ElementName="txtLastName" Path="Text" />
                </MultiBinding>

            </TextBox.Text>
        </TextBox>

Here, the value for TextBox "txtCompleteName" is dependent on two elements viz - txtFirstName and txtLastName.The "Path" property defines the actual property from which to get the data which is "Text" here.

Multibinding needs a multivalue convertor to work properly.If we just omit it and write the below code

<MultiBinding >
	<Binding ElementName="txtFirstName" Path="Text" />
	<Binding ElementName="txtLastName" Path="Text" />
</MultiBinding>

we will get the below error

Cannot set MultiBinding because MultiValueConverter must be specified.

We are using the UpdateSourceTrigger that notifies as soon as the source updates.The value is set to "PropertyChanged"(default property) which states that whenever anything is updated in the control the bound element will reflect the same.

Run the application

Finally let us run the application.When we are typing something in the FirstName field, it is reflecting in the CompleteName textbox.The same is happening for the LastName.

Now we will change the "b" to "B" in "biswas" from the CompleteName field and it should be reflected in the LastName field

Conclusion

This article is written to give an idea of working with IMultiValue convertor.Hope this will be useful.Experiment code is attached herewith.Thanks for reading

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Posted by: Kundan64 on: 2/4/2013 | Points: 25
Very nice article, keep it up.

Login to post response

Comment using Facebook(Author doesn't get notification)