Binding RadioButtons with Gender Property in WPF Using Value Converter

Many WPF developers face a common problem when working with RadioButtons . They try to bind RadioButtons with a Gender property, but the binding does not work as expected . Why does this happen? Because RadioButtons work with true/false values , but in real applications, Gender is stored as meaningful values like: Male Female So the big question is: How do we connect a true/false UI control with a Male/Female data value? Why RadioButton Binding Fails A RadioButton uses the IsChecked property, and this property accepts only: true false But your Gender property is usually: a string ( "Male" , "Female" ) or an enum So the UI value and the data value are different types . This mismatch is the root cause of the problem. The Solution: Value Converter WPF provides a powerful feature called a Value Converter . What is a Value Converter? A Value Converter converts one value type into another. In our case: Convert Gender (...

Step by step guide to implement the command in wpf

To create the custom command we need to implement ICommand interface which is having two method called CanExecute and Execute and one EventHandler called CanExecuteChanged.

  1. CanExecute method is responsible to tell if commend will execute or not.
  2. Execute method perform the action.
Step to create custom command:
  1. Implement the ICommand
  2. write a constructor which will take two parameters of type Action and Func respectively.
  3. if you want to trigger CanExecute on property change then add the method which should invoke CanExecuteChanged  EventHandler .
Why Action?

Action delegate is used for performing the action. As our actual implementation of  this Action will present in our ViewModel and we need to pass ViewModel method as a constructor parameter so that we can assign it in our CustomCommand and can invoke when require.

Why Func?

Func delegate is used when we want to pass some value and return some value. As our actual implementation of  this Func will present in our ViewModel and we need to pass ViewModel method as a constructor parameter so that we can assign it in our CustomCommand and can invoke when require.

public class CustomCommand : ICommand

    {

        public CustomCommand(Action<object> execute, Func<object, bool> canExecute)

        {

            this.execute = execute;

            this.canExecute = canExecute;

        }

        Action<object> execute;

        Func<object, bool> canExecute;

        public event EventHandler CanExecuteChanged;

        public void FireCanExecuteChanged()

        {

            CanExecuteChanged?.Invoke(this, EventArgs.Empty);

        }


        public bool CanExecute(object parameter)

        {

            return canExecute != null && canExecute(parameter);

        }


        public void Execute(object parameter)

        {

            execute?.Invoke(parameter);

        }

    }


How to use this Command in our ViewModel?

public CustomCommand ClickCommand { get; set; }

inside the ViewModel constructor we can instantiate the ClickCommand.


Lets take one example where we have one Textbox, one TextBlock and one Button control.

Now i want to Enable/Disable the button based on Textbox Property.


 <StackPanel>

        <TextBox Text="{Binding Message,UpdateSourceTrigger=PropertyChanged}"/>

        <Button Content="Click" Command="{Binding ClickCommand}"/>

        <TextBlock Text="{Binding MessageText}"/>

  </StackPanel>


ViewModel

public class MainWindowViewModel : INotifyPropertyChanged

    {

        public MainWindowViewModel()

        {

            ClickCommand = new CustomCommand(Execute,CanExecute);

        }


        private bool CanExecute(object arg)

        {

            return !string.IsNullOrEmpty(Message);

        }


        private void Execute(object obj)

        {

            MessageText = "Your text is : " + Message;

        }


        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChnaged(string propertyName)

        {

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        }

        private string _message;


        public string Message

        {

            get { return _message; }

            set

            {

                _message = value;

                OnPropertyChnaged(nameof(Message));

//we have to call this because if the property will change CanExecute will not execute and our Button

//Enable/Disable will not happen

                ClickCommand.FireCanExecuteChanged();

            }

        }

        private string _messageText;


        public string MessageText

        {

            get { return _messageText; }

            set

            {

                _messageText = value;

                OnPropertyChnaged(nameof(MessageText));

            }

        }

       public CustomCommand ClickCommand { get; set; }

    }


I hope this will help you.

                                                                                                            Happy Coding!!!

Comments

Popular posts from this blog

Filter DataGrid and ListView in wpf using ICollectionView

Pagination of DataGrid in WPF using MVVM

How to Create TabControl using Prism Region