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
}
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
}
Add a dictionary with Dictionary and add all your radiobuttons there with the id of your enum then change your enum to this:
public enum MyChoices
{
Choice1 =1,
Choice2 =2,
Choice3 =4
}
And get the enum by this:
RadioButtons[(int)MyChoices.Choice1]
edit:changed my answer
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?
I just thought I'd add the way that I'm currently doing it. There's no 'binding' as such but hopefully it does the same job.
Comments welcome.
public enum MyChoices
{
Choice1,
Choice2,
Choice3
}
public partial class Form1 : Form
{
private Dictionary<int, RadioButton> radButtons;
private MyChoices choices;
public Form1()
{
this.InitializeComponent();
this.radButtons = new Dictionary<int, RadioButton>();
this.radButtons.Add(0, this.radioButton1);
this.radButtons.Add(1, this.radioButton2);
this.radButtons.Add(2, this.radioButton3);
foreach (var item in this.radButtons)
{
item.Value.CheckedChanged += new EventHandler(RadioButton_CheckedChanged);
}
}
private void RadioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton button = sender as RadioButton;
foreach (var item in this.radButtons)
{
if (item.Value == button)
{
this.choices = (MyChoices)item.Key;
}
}
}
public MyChoices Choices
{
get { return this.choices; }
set
{
this.choices = value;
this.SelectRadioButton(value);
this.OnPropertyChanged(new PropertyChangedEventArgs("Choices"));
}
}
private void SelectRadioButton(MyChoices choiceID)
{
RadioButton button;
this.radButtons.TryGetValue((int)choiceID, out button);
button.Checked = true;
}
}