我需要将GroupBox
绑定到BindingSource
,而public class CustomerType
{
public int Id {get; set;}
public string Name {get; set;}
public MemberType MemberType {get; set;}
}
public enum MemberType {Adult, Child}
又绑定到以下对象:
groupBoxMemberType.DataBindings.Add("Selected", this.bindingSource, "MemberType");
我遵循了answer to create a custom GroupBox。我还设置了数据绑定如下:
customerType = customerTypeRequest.Load(id);
bindingSource.DataSource = customerType; //raises exception
但是,在加载现有对象时,我得到以下异常:
DataBinding在列表中找不到适合所有绑定的行。
设置数据源时发生异常:
BindingSource
我错过了什么?是否有替代方法可以将单选按钮绑定到数据源,特别是{{1}}?
答案 0 :(得分:2)
这是更改后的代码:
[DefaultBindingProperty("Selected")]
public class RadioGroupBox : GroupBox
{
#region events
[Description("Occurs when the selected value changes.")]
public event SelectedChangedEventHandler SelectedChanged;
public class SelectedChangedEventArgs : EventArgs
{
public int Selected { get; private set; }
internal SelectedChangedEventArgs(int selected)
{
this.Selected = selected;
}
}
public delegate void SelectedChangedEventHandler(object sender, SelectedChangedEventArgs e);
#endregion
private int selected;
[Browsable(false)]
[Bindable(BindableSupport.Yes, BindingDirection.TwoWay)]
[Description("The selected value associated with this control."), Category("Data")]
public int Selected
{
get { return selected; }
set
{
int val = 0;
var radioButton = this.Controls.OfType<RadioButton>()
.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;
}
protected void OnSelectedChanged(SelectedChangedEventArgs e)
{
if (SelectedChanged != null)
SelectedChanged(this, e);
}
private 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;
OnSelectedChanged(new SelectedChangedEventArgs(selected));
}
}
}
除了将Tag
属性设置为枚举的相应int值之外,还需要在表单中订阅SelectedChanged事件,例如:
private void radioGroupBoxMemberType_SelectedChanged(object sender, SelectedChangedEventArgs e)
{
customerType.MemberType = (MemberType)e.Selected;
}
此课程的改进将是:
从RadioButton继承并使用新属性而不是Tag
属性。
直接在控件中访问并设置bindingsource属性,以避免订阅该事件。