When creating a RadioButton in XAML you can bind the state to the value of an int, as shown in this answer
However if the RadioButton is added to the window in c# code, how can we add this kind of binding?
A button is created as
RadioButton myRadBtn = new RadioButton();
myRadBtn.GroupName = "Some Group";
and I have a converter class ready
public class RadBtnConverter : IValueConverter
{
//Convert a number to radiobutton value by returning true if the radiobutton number (given as the parameter) is the same as the value passed in to convert
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var para = System.Convert.ToInt32(parameter);
var myChoice = System.Convert.ToInt32(value);
return para == myChoice;
}
//Convert the radiobutton to a number by checking isChecked, if true return the parameter as the convertion result, if false say to DoNothing
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var para = System.Convert.ToInt32(parameter);
var isChecked = System.Convert.ToBoolean(value);
return isChecked ? para : Binding.DoNothing;
}
}
Can anyone help?
I'm guessing I need to make a binding and somehow attach it to .Checked or .isCheck, I tried to with:
//myInt is declared in the Window class with public int myInt {get;set;} and initialized to 0 in the class constructor
Binding myBind = new Binding("myInt");
myBind.Source = myInt;
myBind.Converter = new RadBtnConverter();
myBind.Mode = BindingMode.TwoWay;
myBind.ConverterParameter = 5;
myRadBtn.SetBinding(RadioButton.IsCheckedProperty, myBind);
And though that didn't give any errors, the value of myInt remains at 0.