0

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

sanya
  • 111
  • 11

1 Answers1

1

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
}
BionicCode
  • 1
  • 4
  • 28
  • 44
  • 1
    "The simplest solution" - very subjective statement. – ASh Apr 24 '22 at 16:41
  • Yes it is, indeed... – BionicCode Apr 24 '22 at 18:10
  • I wonder that you didn't complain that I haven't defined the `Gender` enum using the FlagsAttribute. – BionicCode Apr 24 '22 at 18:14
  • it seems your ability to over-engineer things is more developed than mine. "define the Gender enum using the FlagsAttribute" - I didn't foresee such twist. – ASh Apr 24 '22 at 18:34
  • Over-engineering - that's good. Imagine a compiler that checks your code for political correctness. Would be nice to join the Roslyn team just to implement this kind of Easter eggs. Like how many developers, especially beginners like students, create a Person class? *"CS6666: A type Person is not allowed to be tested for equality. The equality operator is not meant to discriminate a Person."*... – BionicCode Apr 24 '22 at 19:17