我有4个RadioButtons
和一个方法,我想根据所选的RadioButton
采取不同的行为。我怎么能做这个简单的任务?我应该将每个IsChecked
状态绑定到我ViewModel
中的bool还是有更好的方式?
我认为如果我有更多不同的选项,我会使用ComboBox
并将其选定的索引绑定到我的ViewModel中的int属性。
答案 0 :(得分:1)
我建议为这些选项创建枚举:
public enum MyOptions
{
Option1,
Option2,
Option3
}
然后在ViewModel中创建一个属性,该属性包含此枚举的值:
public class MyViewModel
{
public MyOptions SelectedOption {get;set;} //NotifyPropertyChange() is required.
}
绑定这些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:
...
}
}