如何在Silverlight中为组单选按钮设置数据绑定?

Sliverlight提供了带有GroupName的单选按钮,可以将radiobutton与多个选项中的一个选项组合在一起。 就像是:

   

然后在VM中,我只有一个属性用于此选项,比如它是MyChoice

 public int MyChoice {get; set;} 

那么如何在UI和VM之间为这种情况设置数据绑定?

使用转换器将bools转换为int:

在Xaml上,asssuming选项映射到MyChoice属性上的1,2,3:

     

在转换器中,注意到我没有添加任何强制转换保护:

 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。

您好,您将不得不创建bool类型的三个属性并绑定到RadioButton的IsChecked属性

      

视图模型

  public class ViewModel:INotifyPropertyChanged { bool myChoice1; public bool MyChoice1 { get { return myChoice1; } set { myChoice1 = value; Notify("MyChoice1"); } } bool myChoice2; public bool MyChoice2 { get { return myChoice2; } set { myChoice2 = value; Notify("MyChoice2"); } } bool myChoice3; public bool MyChoice3 { get { return myChoice3; } set { myChoice3 = value; Notify("MyChoice3"); } } public void Notify(string propName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propName)); } public event PropertyChangedEventHandler PropertyChanged; }