使用一组单选按钮作为选择器

时间:2013-08-22 13:13:24

标签: c# wpf radio-button

我有4个RadioButtons和一个方法,我想根据所选的RadioButton采取不同的行为。我怎么能做这个简单的任务?我应该将每个IsChecked状态绑定到我ViewModel中的bool还是有更好的方式?

我认为如果我有更多不同的选项,我会使用ComboBox并将其选定的索引绑定到我的ViewModel中的int属性。

1 个答案:

答案 0 :(得分:1)

我建议为这些选项创建枚举:

public enum MyOptions
{
    Option1,
    Option2,
    Option3
}

然后在ViewModel中创建一个属性,该属性包含此枚举的值:

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

然后使用EnumToBoolConverter

绑定这些RadioButtons
<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}"/>

然后,您确定ViewModel中的简单switch选择了哪个选项:

public void SomeMethod()
{
   switch (SelectedOption)
   {
      case MyOptions.Option1:
           ...
      case MyOptions.Option2:
           ...
      case MyOptions.Option3:
           ...
   }
}