【问题标题】:Using a set of RadioButton as selector使用一组 RadioButton 作为选择器
【发布时间】:2013-08-22 13:13:23
【问题描述】:

我有 4 个RadioButtons 和一个方法,我希望根据所选的RadioButton 表现出不同的行为。我怎么能做这个简单的任务?我应该将每个IsChecked 状态绑定到我的ViewModel 中的一个布尔值还是有更好的方法?

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

【问题讨论】:

标签: c# wpf radio-button


【解决方案1】:

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

public enum MyOptions
{
    Option1,
    Option2,
    Option3
}

然后在 ViewModel 中创建一个属性,该属性包含来自此 Enum 的值:

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:
           ...
   }
}

【讨论】:

    猜你喜欢
    • 2014-03-23
    • 2011-06-17
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    相关资源
    最近更新 更多