2010-03-19 50 views
5

如果我有三个单选按钮,将它们绑定到具有相同选项的枚举的最佳方法是什么?例如Winforms将枚举绑定到单选按钮

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

public enum MyChoices 
{ 
    Choice1, 
    Choice2, 
    Choice3 
} 

回答

1

我知道这是一个古老的问题,但它是第一个显示在我的搜索结果中。我想通了,以单选按钮绑定到一个枚举,甚至是字符串或数字或者一个通用的方法,等等。

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); 
    } 

,然后在你的窗体的构造或形式加载事件,称它在你的每一个RadioButton控件。 dataSource是包含您的枚举属性的对象。我确信dataSource实现了INotifyPropertyChanged接口在enum属性设置器中触发了OnPropertyChanged事件。

AddRadioCheckedBinding(Choice1RadioButton, dataSource, "MyChoice", MyChoices.Choice1); 
AddRadioCheckedBinding(Choice2RadioButton, dataSource, "MyChoice", MyChoices.Choice2); 
2

您可以创建三个布尔属性:

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")); 
} 

然后绑定到MyChoice_Choice1和其他人呢?

0

我只是想我会添加我目前正在做的方式。没有“约束力”,但希望它能完成同样的工作。

评论欢迎。

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; 
    } 
}