Overview Of Multi Binding In MVVM - WPF

Today, in this article, I will explain the multi binding in MVVM, which means if you want to pass the multiple command parameter in MVVM then how to pass it. First, you all are aware of Explain INotifyPropertyChanged In WPF - MVVM and ICommand Interface In MVVM - WPF.

To understand the multi binding, we will take an example, so we create an WPF Application, which contains two text boxes, which contain an integer value and one button. When the user clicks on the button, it will give you the sum. Both these numbers are from the textboxes and the output is displayed in the third textbox. Here, we can say that here on the button command, we have to pass two command parameters number1 and number2, so we have to use multi binding.



Code - MainWindow.xaml
  1. <Window x:Class="MVVM_MultiBinding.MainWindow"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         xmlns:viewmodel="clr-namespace:MVVM_MultiBinding.ViewModel"  
  5.         xmlns:converter="clr-namespace:MVVM_MultiBinding.Converter"  
  6.         Title="MainWindow" Height="350" Width="525">  
  7.     <Window.Resources>  
  8.         <viewmodel:ViewModel x:Key="vm"></viewmodel:ViewModel>  
  9.         <converter:MyValueConverter x:Key="cv"></converter:MyValueConverter>  
  10.     </Window.Resources>  
  11.     <Grid Width="400" Height="200" DataContext="{Binding Source={StaticResource vm}}">  
  12.         <Grid.RowDefinitions>  
  13.             <RowDefinition/>  
  14.             <RowDefinition/>  
  15.             <RowDefinition/>  
  16.             <RowDefinition/>  
  17.             <RowDefinition/>  
  18.         </Grid.RowDefinitions>  
  19.   
  20.         <Grid.ColumnDefinitions>  
  21.             <ColumnDefinition/>  
  22.   
  23.             <ColumnDefinition/>  
  24.         </Grid.ColumnDefinitions>  
  25.   
  26.         <Label Grid.Row="0" Grid.Column="0" Content="Number - 1 : " HorizontalContentAlignment="Right"></Label>  
  27.         <TextBox Grid.Row="0" Grid.Column="1" Name="txtNumb1" Margin="5" Text="{Binding Path=Number1}"></TextBox>  
  28.   
  29.         <Label Grid.Row="1" Grid.Column="0" Content="Number - 2 : " HorizontalContentAlignment="Right"></Label>  
  30.         <TextBox Grid.Row="1" Grid.Column="1" Name="txtNumb2"  Margin="5" Text="{Binding Path=Number2}"></TextBox>  
  31.   
  32.   
  33.         <Button Grid.Row="2" Grid.Column="1" Margin="5" Content="SUM" Command="{Binding Path=MyCommand}">  
  34.              
  35.         </Button>  
  36.   
  37.         <Label Grid.Row="3" Grid.Column="0" Content="Sum : " HorizontalContentAlignment="Right"></Label>  
  38.         <TextBox Grid.Row="3" Grid.Column="1" Margin="5" Text="{Binding Path=NumberSum, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>  
  39.     </Grid>  
  40. </Window>  
Here, in the example, mentioned above, we take one RelayCommand Class, which you already know, if you are not aware of this then read ICommand Interface In MVVM - WPF.

Code - RealyCommand.sc
  1. public class RelayCommand:ICommand  
  2. {  
  3.   
  4.         Action<object> _execute;  
  5.         Func<object, bool> _canexecute;  
  6.         public RelayCommand(Action<object> execute,Func<object,bool> canexecute)  
  7.         {  
  8.             _execute = execute;  
  9.             _canexecute = canexecute;  
  10.   
  11.         }  
  12.         public bool CanExecute(object parameter)  
  13.         {  
  14.             if (_canexecute != null)  
  15.             {  
  16.                 return _canexecute(parameter);  
  17.             }  
  18.             else  
  19.             {  
  20.                 return false;  
  21.             }  
  22.         }  
  23.   
  24.         public event EventHandler CanExecuteChanged  
  25.         {  
  26.             add { CommandManager.RequerySuggested += value; }  
  27.             remove { CommandManager.RequerySuggested -= value; }  
  28.         }  
  29.   
  30.         public void Execute(object parameter)  
  31.         {  
  32.             _execute(parameter);  
  33.         }  
  34.     }  
Now, we want one view model, which contains ‘Number1’,’Number2’ and ‘NumberSum’ property. It stores the value and it binds to the respective text box. Also, this view mode implements INotifyPropertyChanged interface, as we learnt in Explain INotifyPropertyChanged In WPF - MVVM article.

Code - Viewmodel.cs
  1. public class ViewModel : INotifyPropertyChanged  
  2. {  
  3.  public ICommand MyCommand { get; set; }  
  4.         public event PropertyChangedEventHandler PropertyChanged;  
  5.   
  6.   
  7.         private void OnPropertyChanged( string propertyname)  
  8.         {  
  9.             if (PropertyChanged != null)  
  10.             {  
  11.                 PropertyChanged(thisnew PropertyChangedEventArgs(propertyname));  
  12.             }  
  13.         }  
  14.   
  15.         private int _number1;  
  16.         public int Number1  
  17.         {  
  18.             get { return _number1; }  
  19.             set { _number1 = value; OnPropertyChanged("Number1"); }  
  20.         }  
  21.   
  22.   
  23.         private int _number2;  
  24.         public int Number2  
  25.         {  
  26.             get { return _number2; }  
  27.             set { _number2 = value; OnPropertyChanged("Number2"); }  
  28.         }  
  29.   
  30.   
  31.         private int nubersum;  
  32.   
  33.         public int NumberSum  
  34.         {  
  35.             get { return nubersum; }  
  36.             set { nubersum = value; OnPropertyChanged("NumberSum"); }  
  37.         }  
  38.   
  39.   
  40.         public ViewModel()  
  41.         {  
  42.             MyCommand = new MVVM_MultiBinding.RelayCommand.RelayCommand(execute, canexecute);  
  43.         }  
  44.   
  45.   
  46.         private bool canexecute(object parameter)  
  47.         {  
  48.             if (Number1 !=null || Number2 != null)  
  49.             {  
  50.                    return true;  
  51.             }  
  52.             else { return false; }  
  53.         }  
  54.   
  55.         private void execute(object parameter)  
  56.         {  
  57.               
  58.         }  
  59.   
  60.     }  
If you want to use multi binding, you have to use the Multi value converter interface, so we create a converter class and implement it with IMultiValueConvetr interface.

Code - MyValueConverter.cs
  1. public class MyValueConverter:IMultiValueConverter  
  2.     {  
  3.         public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
  4.         {  
  5.             return values.Clone();  
  6.         }  
  7.   
  8.         public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)  
  9.         {  
  10.             return null;  
  11.         }  
  12.     }  
Now, we give this viewmodel and Myconverter class as a referance to the view(UI). It also defines the Window resources property and assigns a unique key to it, in addition to setting the data context property of the parent control, as we discussed in the previous articles  Explain INotifyPropertyChanged In WPF - MVVM and ICommand Interface In MVVM - WPF

Now, we come to our main part like button control. Here, when the user clicks on the button, we have to pass two command parameters, which are given below.
  1. <Button Grid.Row="2" Grid.Column="1" Margin="5" Content="SUM" Command="{Binding Path=MyCommand}">  
  2.             <Button.CommandParameter>  
  3.                 <MultiBinding Converter="{StaticResource cv }">  
  4.                     <Binding ElementName="txtNumb1" Path="Text"/>  
  5.                     <Binding ElementName="txtNumb2" Path="Text"/>  
  6.                 </MultiBinding>  
  7.             </Button.CommandParameter>  
  8.         </Button>  
As shown in the code, given above, we define Button.Command Parameter tag. In this tag, we define the Multi binding tags and pass the converter source with them. Subsequently, we pass our parameter in Binding tag. We pass the element name and path for the command parameter. Please keep in mind here in whatever sequence you pass in the parameter, you will get this in the same sequence  on the view model side.

Move to the view model side and go to execute the method here. We receive the parameter object, so we convert it to the object array. Subsequently, from the array, we get both the parameters by passing an array index. Additionally, we convert it to the integer, make sum of them and assign it to ‘NumberSum’.
  1. private void execute(object parameter)  
  2.         {  
  3.             var values = (object[])parameter;  
  4.             int num1 = Convert.ToInt32((string)values[0]);  
  5.             int num2 = Convert.ToInt32((string)values[1]);  
  6.             NumberSum = num1+num2;  
  7.         }  
Now, run the Application and check the result.

result