Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms Bind Enum to Radio Buttons

If I have three radio buttons, what is the best way to bind them to an enum which has the same choices? e.g.

[] Choice 1
[] Choice 2
[] Choice 3

public enum MyChoices
{
    Choice1,
    Choice2,
    Choice3
}
like image 834
Damien Avatar asked Mar 19 '10 11:03

Damien


2 Answers

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);
like image 199
WeskerTyrant Avatar answered Oct 13 '22 16:10

WeskerTyrant


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?

like image 2
Simon Avatar answered Oct 13 '22 18:10

Simon