我正在研究一些现有的Windows窗体的数据绑定,并且我遇到了一个问题,想出了在一个组框内数据绑定一组radiobutton控件的正确方法.
我的业务对象有一个整数属性,我想对4个radiobuttons进行数据绑定(其中每个都代表值0 - 3).
我目前正在绑定一个presenter对象,它作为表单和业务对象之间的绑定器,我现在的方式是拥有4个独立的属性,每个属性都绑定这些值(我使用INotifyPropertyChanged) ,但不包括这里):
Private int _propValue; Public bool PropIsValue0 { get { return _propValue == 0; } set { if (value) _propValue = 0; } } Public bool PropIsValue1 { // As above, but with value == 1 } Public bool PropIsValue2 { // As above, but with value == 2 } Public bool PropIsValue3 { // As above, but with value == 3 }
然后我将每个单选按钮绑定到它们各自的属性,如上所述.
这对我来说似乎不对,所以任何建议都受到高度赞赏.
下面是一个通用的RadioGroupBox实现,本着ArielBH的建议(一些代码借用了Jay Andrew Allen的RadioPanel).只需向其添加RadioButtons,将其标记设置为不同的整数并绑定到"Selected"属性.
public class RadioGroupBox : GroupBox { public event EventHandler SelectedChanged = delegate { }; int _selected; public int Selected { get { return _selected; } set { int val = 0; var radioButton = this.Controls.OfType() .FirstOrDefault(radio => radio.Tag != null && int.TryParse(radio.Tag.ToString(), out val) && val == value); if (radioButton != null) { radioButton.Checked = true; _selected = val; } } } protected override void OnControlAdded(ControlEventArgs e) { base.OnControlAdded(e); var radioButton = e.Control as RadioButton; if (radioButton != null) radioButton.CheckedChanged += radioButton_CheckedChanged; } void radioButton_CheckedChanged(object sender, EventArgs e) { var radio = (RadioButton)sender; int val = 0; if (radio.Checked && radio.Tag != null && int.TryParse(radio.Tag.ToString(), out val)) { _selected = val; SelectedChanged(this, new EventArgs()); } } }
请注意,由于InitializeComponent中的初始化顺序问题,您无法通过设计器绑定到"Selected"属性(绑定在初始化单选按钮之前执行,因此在第一次分配时它们的标记为null).所以就像这样绑定自己:
public Form1() { InitializeComponent(); //Assuming selected1 and selected2 are defined as integer application settings radioGroup1.DataBindings.Add("Selected", Properties.Settings.Default, "selected1"); radioGroup2.DataBindings.Add("Selected", Properties.Settings.Default, "selected2"); }