Home > Software design >  WPF MVVM - How do I bind a radio button to a property
WPF MVVM - How do I bind a radio button to a property

Time:04-25

I have a gender property:

public string Gender
{
    get { return _gender; }
    set
    {
        _gender = value;
        OnPropertyChanged();
    }
}

And two radio buttons to select two available genders:

 <RadioButton  GroupName="Group1" Content="Male"/>
 <RadioButton  GroupName="Group1" Content="Female"/>

what I wanted to do was to set the gender string to either Male or Female depending on which radio button is selected purely from data biding without code behind, is that possible if so can someone explain? I already did this for a textbox I'm just not sure how to go about a radio button

CodePudding user response:

A simple solution is to use a RadioButton.Command and the RadioButton.CommandParameter. Alternatively, but with slightly more overhead, use a Binding or MultiBinding with a IValueConverter.

Also, you should not handle plain strings. Better define an enum e.g. Gender:

MainWindow.xaml

<StackPanel>
  <RadioButton Command="{Binding SetGenderCommand}"
               CommandParameter="{x:Static local:Gender.Male}" />
  <RadioButton Command="{Binding SetGenderCommand}"
               CommandParameter="{x:Static local:Gender.Female}" />
</StackPanel>

MainViewModel.cs

class MainViewModel : INotifyPropertyChanged
{
  // Raises PropertyChanged
  public Gender Gender { get; set; }

  public ICommand SetGenderCommand => new RoutedCommand(ExecuteSetGenderCommand);

  private void ExecuteSetGenderCommand(object commandParameter)
    => this.Gender = (Gender)commandParameter;
}

Gender.cs

public enum Gender
{
  Default = 0,
  Female,
  Male
}
  • Related