问题描述
Sliverlight提供带有GroupName的单选按钮,用于对单选按钮进行分组,以及多选项中的一个选项。这就像:
Sliverlight provides radio button with GroupName to group radiobutton together with only one option from mutiple choice. It's like:
<RadioButton GroupName="Option" Content="Option 1"></RadioButton>
<RadioButton GroupName="Option" Content="Option 2"></RadioButton>
<RadioButton GroupName="Option" Content="Option 3"></RadioButton>
然后在VM中,我只有一个属性用于此选项,说是MyChoice
then in VM, I have only one property for this option,say it's MyChoice
public int MyChoice {get; set;}
那么如何在UI和VM之间为这种情况设置数据绑定?
then how to setup data binding for this case between UI and VM?
推荐答案
使用转换器将bools转换为int:
Used a converter to convert bools to an int:
在Xaml,asssuming选项映射到您的MyChoice属性上的1,2,3:
On Xaml, asssuming options map to 1,2,3 on your MyChoice property:
<RadioButton GroupName="Option" Content="Option 1"
IsChecked="{Binding Path=MyChoice, Converter={StaticResource RadioButtonToIntConverter},
ConverterParameter=1}"/>
<RadioButton GroupName="Option" Content="Option 2"
IsChecked="{Binding Path=MyChoice, Converter={StaticResource RadioButtonToIntConverter},
ConverterParameter=2}"/>
<RadioButton GroupName="Option" Content="Option 3"
IsChecked="{Binding Path=MyChoice, Converter={StaticResource RadioButtonToIntConverter},
ConverterParameter=3}"/>
在转换器中,注意到我没有添加任何转换保护:
In the converter, noting that I did not add any cast protection:
public class RadioButtonToIntConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var para = System.Convert.ToInt32(parameter);
var myChoice = System.Convert.ToInt32(value);
return para == myChoice;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var para = System.Convert.ToInt32(parameter);
var isChecked = System.Convert.ToBoolean(value);
return isChecked ? para : Binding.DoNothing;
}
}
最好在您的ViewModel中实现INotifyPropertyChanged 。
Also you'd better to implement INotifyPropertyChanged in you ViewModel.
这篇关于如何在Silverlight中设置组单选按钮的数据绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!