0

I have 4 RadioButtons and a method that I want to behave differently depending on the selected RadioButton. How could I do this simple task? Should I bind each IsChecked state to a bool in my ViewModel or there is a better way?

I think that if I had more different options I would do it with a ComboBox and binding its selected index to a int property in my ViewModel.

Sturm
  • 3,968
  • 10
  • 48
  • 78
  • 1
    possible duplicate of [How to get the value of the checked radiobutton in wpf](http://stackoverflow.com/questions/16036469/how-to-get-the-value-of-the-checked-radiobutton-in-wpf) – Sheridan Aug 22 '13 at 13:29

1 Answers1

1

I recommend creating an Enum for these options:

public enum MyOptions
{
    Option1,
    Option2,
    Option3
}

Then create a property in the ViewModel which holds a value from this Enum:

public class MyViewModel
{
    public MyOptions SelectedOption {get;set;} //NotifyPropertyChange() is required.
}

Then bind these RadioButtons using the EnumToBoolConverter

<RadioButton IsChecked="{Binding SelectedOption, Converter={StaticResource EnumToBoolConverter}, ConverterParameter=Option1}"/>
<RadioButton IsChecked="{Binding SelectedOption, Converter={StaticResource EnumToBoolConverter}, ConverterParameter=Option2}"/>
<RadioButton IsChecked="{Binding SelectedOption, Converter={StaticResource EnumToBoolConverter}, ConverterParameter=Option3}"/>

Then, you determine which option is selected by a simple switch in the ViewModel:

public void SomeMethod()
{
   switch (SelectedOption)
   {
      case MyOptions.Option1:
           ...
      case MyOptions.Option2:
           ...
      case MyOptions.Option3:
           ...
   }
}
Community
  • 1
  • 1
Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154