Winforms Bind Enum to Radio Buttons
I know this is an old question, but it was the first to show up in my search results. I figured out a generic way to bind radio buttons to an enum, or even a string or number, etc.
private void AddRadioCheckedBinding<T>(RadioButton radio, object dataSource, string dataMember, T trueValue)
{
var binding = new Binding(nameof(RadioButton.Checked), dataSource, dataMember, true, DataSourceUpdateMode.OnPropertyChanged);
binding.Parse += (s, a) => { if ((bool)a.Value) a.Value = trueValue; };
binding.Format += (s, a) => a.Value = ((T)a.Value).Equals(trueValue);
radio.DataBindings.Add(binding);
}
And then either on your form's constructor or on the form load event, call it on each of your RadioButton
controls.
The dataSource
is the object containing your enum property. I made sure that dataSource
implemented the INotifyPropertyChanged
interface is firing the OnPropertyChanged
event in the enum properties setter.
AddRadioCheckedBinding(Choice1RadioButton, dataSource, "MyChoice", MyChoices.Choice1);
AddRadioCheckedBinding(Choice2RadioButton, dataSource, "MyChoice", MyChoices.Choice2);
Could you create three boolean properties:
private MyChoices myChoice;
public bool MyChoice_Choice1
{
get { return myChoice == MyChoices.Choice1; }
set { if (value) myChoice = MyChoices.Choice1; myChoiceChanged(); }
}
// and so on for the other two
private void myChoiceChanged()
{
OnPropertyChanged(new PropertyChangedEventArgs("MyChoice_Choice1"));
OnPropertyChanged(new PropertyChangedEventArgs("MyChoice_Choice2"));
OnPropertyChanged(new PropertyChangedEventArgs("MyChoice_Choice3"));
}
then bind to MyChoice_Choice1 and the others?