CheckBox Binding In MVVM - WPF

Today, I will explain how to use checkbox in WPF using MVVM pattern. Before starting this article please read Explain INotifyPropertyChanged In WPF - MVVM and ICommand Interface In MVVM - WPF article.

Let’s take an example to create one WPF Application, put four check boxes and put one text box in it. The user has to select the check box and whatever check box the user selects, you have to display the list of all the checked checkboxes in the text box.

Thus, we create a WPF Window, as shown below.



Code - MainWindow.xaml

  1. <Window x:Class="MVVM_Checkbox.View.Window1"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         Title="Window1" Height="350" Width="525">  
  5.     <StackPanel Orientation="Vertical" Margin="20" >  
  6.         <CheckBox Width="120" Name="cbIndia" Content="India"></CheckBox>  
  7.         <CheckBox Width="120" Name="cbUS" Content="US"></CheckBox>  
  8.         <CheckBox Width="120" Name="cbUK" Content="UK"></CheckBox>  
  9.         <CheckBox Width="120" Name="cbChina" Content="China"></CheckBox>  
  10.         <TextBox Width="300" Margin="20"></TextBox>  
  11.     </StackPanel>  
  12. </Window>  
Here, when the user checked the checkbox, we have to display its selected checkbox content in the textbox, so first we have to create a command for the checkbox, which is checked. In simple words, we have to create a checkbox, which is checked on the change of the event in Windows form Application, but in MVVM pattern, we say that we have to create a command for the same. Thus, we create the Relay Command class, which implements the ICommand interface. This is taught in the   ICommand Interface In MVVM - WPF article.

Code - RalayCommand.cs
  1. public class RelayCommand:ICommand  
  2.     {  
  3.         Action<object> _executemethod;  
  4.         Func<object, bool> _canexecutemethod;  
  5.   
  6.         public RelayCommand(Action<object> executemethod,Func<object,bool> canexecutemethod)  
  7.         {  
  8.             _executemethod = executemethod;  
  9.             _canexecutemethod = canexecutemethod;  
  10.         }  
  11.   
  12.         public bool CanExecute(object parameter)  
  13.         {  
  14.             if (_executemethod != null)  
  15.             {  
  16.                 return _canexecutemethod(parameter);  
  17.             }else  
  18.             {  
  19.                 return false;  
  20.             }  
  21.         }  
  22.   
  23.         public event EventHandler CanExecuteChanged  
  24.         {  
  25.             add { CommandManager.RequerySuggested += value; }  
  26.             remove { CommandManager.RequerySuggested -= value; }  
  27.         }  
  28.   
  29.         public void Execute(object parameter)  
  30.         {  
  31.             _executemethod(parameter);  
  32.         }  
  33.     }  
Now we have to make view-model class in which we have to define two properties.
  1. String Name;  
  2. ObservableCollection<String> Countries;  
Here ‘Name’ property is used to store the selected countries' names, as shown in the single string. When the user selects any country, we concat the checkbox name in this ‘Name’ property and when it is unchecked, we remove this name from the string. Finally, we bind this property ‘Name’ to the text box.

‘Countries’ property contains the one type of collection of the string. Here, we take the string as the country name. Based on checked and un-checked of check box, we add or remove the country name from the collection.

Now, we have to implement the INotifyPropertyChanged interface to update the UI, based on the change in view-model, which was discussed in Explain INotifyPropertyChanged In WPF - MVVM.
  1. public class ViewModel:INotifyPropertyChanged  
  2.     {  
  3.           
  4.         private ObservableCollection<string> _countries;  
  5.         public ObservableCollection<string> Countries  
  6.         {  
  7.             get { return _countries; ; }  
  8.             set  
  9.             {  
  10.                 _countries = value;  
  11.                 OnPropertyChange("Countries");  
  12.             }  
  13.         }  
  14.   
  15.   
  16.         private string _name;  
  17.         public string Name  
  18.         {  
  19.             get { return _name; }  
  20.             set   
  21.             {   
  22.                 _name = value;  
  23.                 OnPropertyChange("Name");  
  24.             }  
  25.         }     
  26. public event PropertyChangedEventHandler PropertyChanged;  
  27.   
  28.         private void OnPropertyChange(string propertyname)  
  29.         {  
  30.             if (PropertyChanged !=null)  
  31.             {  
  32.                 PropertyChanged(thisnew PropertyChangedEventArgs(propertyname));  
  33.             }  
  34.         }  
  35.   
  36.   
  37.   
  38.     }  
Now, we define the ICommand for the fire.
  1. public ICommand MyCommand { get; set; }  
Also, we create two new methods - canexecute and execute, where canexecute allows to fire execute method or not. On the other hand, execute method contains the actual logic like assigning all the checked check box values to the ‘Name’ property.

When command fires from the view screen, we have to decide that, whether the user checks the check box or un-checks the check box. Base on its action we perform our further operation. In command parameters, we have to pass multiple (two) parameters, where one is check box content name and another is "IsChecked". Thus, we have to use Multi Binding. Multi Binding is already discussed in Explain Multi Binding In MVVM - WPF article.
  1. private bool canexecutemethod(object parameter)  
  2.         {  
  3.             return true;  
  4.         }  
  5.   
  6.         private void executemethod(object parameter)  
  7.         {  
  8.             var values = (object[])parameter;  
  9.             string name = (string)values[0];  
  10.             bool check = (bool)values[1];  
  11.             if (check)  
  12.             {  
  13.                 Countries.Add(name);  
  14.             }  
  15.             else  
  16.             {  
  17.                 Countries.Remove(name);  
  18.             }  
  19.               
  20.             Name = "";  
  21.             foreach (string item in Countries)  
  22.             {  
  23.                 Name = Name + item;  
  24.             }  
  25.   
  26.  }  
Here, I will explain the function, given above. First, we receive the collection as a parameter collection, which contains two values, where one is checkbox content name and second is IsChecked property. Now, we separate string and Boolean variable.

Subsequently, we check is IsChecked is true then we need to add this checkbox content name to our collection and if it’s false, we remove it from our collection.

Finally, we take all the country names from the collection and store it in the single string, using for loop.

Now, we create the multi value converter, as we discussed in Explain Multi Binding In MVVM - WPF article, if you want to use multi binding , you have to use I value converter.

Code - MyConverter.cs
  1. public class MyConverter:IMultiValueConverter  
  2.     {  
  3.         public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
  4.         {  
  5.                 return values.Clone();  
  6.         }  
  7.   
  8.   
  9.         public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)  
  10.         {  
  11.             return null;  
  12.         }  
  13.     }  
Now, go to the view and give reference of the view-mode and converter to the view
  1. xmlns:viewmodel="clr-namespace:MVVM_Checkbox.ViewModel"  
  2. xmlns:converter="clr-namespace:MVVM_Checkbox.Converter"  
Create the Window resource property and assign the unique key to it.
  1. <Window.Resources>  
  2.    <viewmodel:ViewModel x:Key="vm"></viewmodel:ViewModel>  
  3.    <converter:MyConverter x:Key="cv"></converter:MyConverter>  
  4. </Window.Resources>  
Now, set the data context value for the parent control.
  1. <StackPanel Orientation="Vertical" Margin="20" DataContext="{Binding Source={StaticResource vm}}">  
Now, we will assign the command property to the checkbox and then we set the command parameter to the checkbox. Here, we use multi binding. We disused it in previous article Explain Multi Binding In MVVM - WPF.
  1. <CheckBox Width="120" Name="cbIndia" Content="India" Command="{Binding MyCommand}">  
  2.             <CheckBox.CommandParameter>  
  3.                 <MultiBinding Converter="{StaticResource cv}">  
  4.                     <Binding ElementName="cbIndia" Path="Content"/>  
  5.                     <Binding ElementName="cbIndia" Path="IsChecked"/>  
  6.                 </MultiBinding>  
  7.             </CheckBox.CommandParameter>  
  8.         </CheckBox>  
Now, we set the text property of the text box as ‘Name’.
  1. <TextBox Width="300" Margin="20" Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>  
Code - MainWindow.xaml
  1. <Window x:Class="MVVM_Checkbox.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_Checkbox.ViewModel"  
  5.         xmlns:converter="clr-namespace:MVVM_Checkbox.Converter"  
  6.         Title="MainWindow" Height="350" Width="525">  
  7.     <Window.Resources>  
  8.         <viewmodel:ViewModel x:Key="vm"></viewmodel:ViewModel>  
  9.         <converter:MyConverter x:Key="cv"></converter:MyConverter>  
  10.     </Window.Resources>  
  11.     <StackPanel Orientation="Vertical" Margin="20" DataContext="{Binding Source={StaticResource vm}}">  
  12.         <CheckBox Width="120" Name="cbIndia" Content="India" Command="{Binding MyCommand}">  
  13.             <CheckBox.CommandParameter>  
  14.                 <MultiBinding Converter="{StaticResource cv}">  
  15.                     <Binding ElementName="cbIndia" Path="Content"/>  
  16.                     <Binding ElementName="cbIndia" Path="IsChecked"/>  
  17.                 </MultiBinding>  
  18.             </CheckBox.CommandParameter>  
  19.         </CheckBox>  
  20.         <CheckBox Width="120" Name="cbUS" Content="US" Command="{Binding MyCommand}">  
  21.             <CheckBox.CommandParameter>  
  22.                 <MultiBinding Converter="{StaticResource cv}">  
  23.                     <Binding ElementName="cbUS" Path="Content"/>  
  24.                     <Binding ElementName="cbUS" Path="IsChecked"/>  
  25.                 </MultiBinding>  
  26.             </CheckBox.CommandParameter>  
  27.         </CheckBox>  
  28.         <CheckBox Width="120" Name="cbUK" Content="UK" Command="{Binding MyCommand}">  
  29.             <CheckBox.CommandParameter>  
  30.                 <MultiBinding Converter="{StaticResource cv}">  
  31.                     <Binding ElementName="cbUK" Path="Content"/>  
  32.                     <Binding ElementName="cbUK" Path="IsChecked"/>  
  33.                 </MultiBinding>  
  34.             </CheckBox.CommandParameter>  
  35.         </CheckBox>  
  36.         <CheckBox Width="120" Name="cbChina" Content="China" Command="{Binding MyCommand}">  
  37.             <CheckBox.CommandParameter>  
  38.                 <MultiBinding Converter="{StaticResource cv}">  
  39.                     <Binding ElementName="cbChina" Path="Content"/>  
  40.                     <Binding ElementName="cbChina" Path="IsChecked"/>  
  41.                 </MultiBinding>  
  42.             </CheckBox.CommandParameter>  
  43.         </CheckBox>  
  44.         <TextBox Width="300" Margin="20" Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>  
  45.     </StackPanel>  
  46. </Window>  
Now, run the Application and show the output.