Explain Radio Button Binding In MVVM - WPF

Today, I will explain to you about binding the radio button in WPF, using MVVM pattern. In my previous article, you learned about combo box binding in WPF using MVVM pattern. Before we start, I want to ask have you ever gone through the concept of INotifyPropertyChanged and ICommand interface? It's the most important part of the MVVM pattern, so if you have any confusion regarding both these interfaces, please read my previous article, whose links are given below.

  1. Explain INotifyPropertyChanged In WPF - MVVM
  2. ICommand Interface In MVVM - WPF

We will make one example in which we display four radio buttons and one text box. When the user selects any radio button, we have to display this radio button content in text box, so lets start.

  1. Create simple WPF Application with four radio buttons and one text box, as shown below.



    Code - MainWindow.xaml

    1. <Window x:Class="MVVM_RadioButton.View.MainWindow"  
    2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    4.         Title="Main Window" Height="350" Width="525">  
    5.     <StackPanel Orientation="Vertical" Margin="20">  
    6.         <RadioButton Width="150" Content="India" Name="cbIndia" IsChecked="True"></RadioButton>  
    7.         <RadioButton Width="150" Content="USA" Name="cbUSA"></RadioButton>  
    8.         <RadioButton Width="150" Content="UK"  Name="cbUK"></RadioButton>  
    9.         <RadioButton Width="150" Content="China" Name="cbChina"></RadioButton>  
    10.         <TextBox Width="120" Margin="20"></TextBox>  
    11.     </StackPanel>  
    12. </Window>  
  2. When a user changes the selection, we have to display its selected radio button content in the textbox, so first we have to command for the radio button selection change. In simple words, we have to create radio button selection, change event in Windows form Application but in MVVM pattern, we say that we have to create command for the same. Thus, we create the Relay Command class, which implements the ICommand interface. This is already learned in (ICommand Interface In MVVM - WPF) article.

    Code - RelayCommand.cs
    1. public class RelayCommand:ICommand  
    2.     {  
    3.   
    4.         Action<object> _executemethod;  
    5.         Func<object, bool> _canexecutemethod;  
    6.   
    7.         public RelayCommand(Action<object> executemethod,Func<object,bool> canexecutemethod)  
    8.         {  
    9.             _executemethod = executemethod;  
    10.             _canexecutemethod = canexecutemethod;  
    11.         }  
    12.   
    13.   
    14.         public bool CanExecute(object parameter)  
    15.         {  
    16.             if (_canexecutemethod != null)  
    17.             {  
    18.                 return _canexecutemethod(parameter);  
    19.             }  
    20.             else  
    21.             {  
    22.                 return false;  
    23.             }  
    24.         }  
    25.   
    26.         public event EventHandler CanExecuteChanged  
    27.         {  
    28.             add { CommandManager.RequerySuggested += value; }  
    29.             remove { CommandManager.RequerySuggested -= value; }  
    30.         }  
    31.   
    32.         public void Execute(object parameter)  
    33.         {  
    34.             _executemethod(parameter);  
    35.         }  
    36.     }  
  3. Now, we have to make one view-model class, which has one property ‘Name’ with Get and Set method. When the user changes the radio button selection, we update this property value and we bind this property to the textbox, so it will display the user selected radio button content into the text box.

  4. When we change the ‘Name’ property, we have to inform UI (view) to display the changes. We need INotifyPropertyChanged interface, so we implement this interface and fire the property change event when ‘Name’ value changes.
    1. public class ViewModel :INotifyPropertyChanged  
    2.     {  
    3.   
    4.         private string _name;  
    5.         public string Name  
    6.         {  
    7.             get { return _name; }  
    8.             set   
    9.             {   
    10.                 _name = value;  
    11.                 OnPropertyChange("Name");  
    12.             }  
    13.         }  
    14.           
    15.   
    16.         public event PropertyChangedEventHandler PropertyChanged;  
    17.   
    18.         private void OnPropertyChange(string propertyname)  
    19.         {  
    20.             if (PropertyChanged !=null)  
    21.             {  
    22.                 PropertyChanged(thisnew PropertyChangedEventArgs(propertyname));  
    23.             }  
    24.         }  
    25.     }  
  5. As far as details of INotifyPropertyChanged interface are concerned, we have already learnt in the previous article (Explain INotifyPropertyChanged In WPF - MVVM).

    Now, we create the ICommand property in view model class.
    1. public ICommand MyCommand { get; set; }  
  6. We create two method canexecute and execute, where canexecute decides to fire an execute method or not. It is an execute method, which contains the actual logic like assigning radio button value to the ‘Name’ property.
    1. private bool canexecutemethod(object parameter)  
    2.         {  
    3.             if (parameter != null)  
    4.             {  
    5.                 return true;  
    6.             }  
    7.             else  
    8.             {  
    9.                 return false;  
    10.             }  
    11.         }  
    12.   
    13.         private void executemethod(object parameter)  
    14.         {  
    15.             Name = (string)parameter;  
    16.         }  
  7. Now, we declare MyCommand in the constructor of the view-model class and pass these both methods to it.
    1. public ViewModel()  
    2.         {  
    3.             MyCommand = new RelayCommand(executemethod, canexecutemethod);  
    4.         }  
    Full Code - ViewModel.cs
    1. public class ViewModel :INotifyPropertyChanged  
    2.     {  
    3.   
    4.         public ICommand MyCommand { get; set; }  
    5.         private string _name;  
    6.         public string Name  
    7.         {  
    8.             get { return _name; }  
    9.             set   
    10.             {   
    11.                 _name = value;  
    12.                 OnPropertyChange("Name");  
    13.             }  
    14.         }  
    15.           
    16.   
    17.         public ViewModel()  
    18.         {  
    19.             MyCommand = new RelayCommand(executemethod, canexecutemethod);  
    20.         }  
    21.   
    22.         public event PropertyChangedEventHandler PropertyChanged;  
    23.   
    24.         private void OnPropertyChange(string propertyname)  
    25.         {  
    26.             if (PropertyChanged !=null)  
    27.             {  
    28.                 PropertyChanged(thisnew PropertyChangedEventArgs(propertyname));  
    29.             }  
    30.         }  
    31.   
    32.   
    33.   
    34.         private bool canexecutemethod(object parameter)  
    35.         {  
    36.             if (parameter != null)  
    37.             {  
    38.                 return true;  
    39.             }  
    40.             else  
    41.             {  
    42.                 return false;  
    43.             }  
    44.         }  
    45.   
    46.         private void executemethod(object parameter)  
    47.         {  
    48.             Name = (string)parameter;  
    49.         }  
    50.     }  
  8. Now, move to the view(UI) side. First, we have to give view-model reference to the view, so we define the namespace for view-mode in the view.
    1. xmlns:viewmodel="clr-namespace:MVVM_RadioButton.ViewModel"  
  9. Also, define Window resource property and give unique key to it.
    1. <Window.Resources>  
    2.    <viewmodel:ViewModel x:Key="vm"></viewmodel:ViewModel>  
    3. </Window.Resources>  
  10. Set data context property for the parent control (stack panel).
    1. <StackPanel Orientation="Vertical" DataContext="{Binding Source={StaticResource vm}}" Margin="20">  
  11. Now, see the command property for the all four radio buttons.
    1. <RadioButton   
    2.    Width="150"   
    3.    Content="India"   
    4.    Command="{Binding Path=MyCommand}"   
    5.    Name="cbIndia">  
    6.   
    7. </RadioButton>  
    Do the same for all four radio buttons.

  12. Also, set the command parameter property for the radio button and pass the radio button content value to it. Because whatever parameter you pass here, it will assign to ‘Name’ property in view model and it displays in the textbox, so here we pass name radio button content value as a parameter.
    1. <RadioButton   
    2.    Width="150"   
    3.    Content="India"   
    4.    Command="{Binding Path=MyCommand}"   
    5.    Name="cbIndia"   
    6.    CommandParameter="{Binding ElementName=cbIndia, Path=Content}">  
    7.   
    8. </RadioButton>  
    Do the same for all four radio buttons.

  13. Now, we bind the ‘Name’ property to the text box.
    1. <TextBox   
    2.    Width="120"   
    3.    Margin="20"   
    4.    Text="{Binding Path=Name, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">  
    5. </TextBox>  
    Full Code - MainWindow.xaml
    1. <Window x:Class="MVVM_RadioButton.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_RadioButton.ViewModel"  
    5.         Title="MainWindow" Height="350" Width="525">  
    6.     <Window.Resources>  
    7.         <viewmodel:ViewModel x:Key="vm"></viewmodel:ViewModel>  
    8.     </Window.Resources>  
    9.     <StackPanel Orientation="Vertical" DataContext="{Binding Source={StaticResource vm}}" Margin="20">  
    10.         <RadioButton Width="150" Content="India" Command="{Binding Path=MyCommand}" Name="cbIndia" CommandParameter="{Binding ElementName=cbIndia, Path=Content}"></RadioButton>  
    11.         <RadioButton Width="150" Content="USA" Command="{Binding Path=MyCommand}" Name="cbUSA" CommandParameter="{Binding ElementName=cbUSA, Path=Content}"></RadioButton>  
    12.         <RadioButton Width="150" Content="UK" Command="{Binding Path=MyCommand}" Name="cbUK" CommandParameter="{Binding ElementName=cbUK, Path=Content}"></RadioButton>  
    13.         <RadioButton Width="150" Content="China" Command="{Binding Path=MyCommand}" Name="cbChina" CommandParameter="{Binding ElementName=cbChina, Path=Content}"></RadioButton>  
    14.         <TextBox Width="120" Margin="20" Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>  
    15.     </StackPanel>  
    16. </Window>  
  14. Now, run the Application and check the output by changing the selection of the radio button.


Thanks for reading my article. If you have any confusion, type it in the comment section.