保存数据后,Combobox的行为不符合预期

时间:2017-08-29 12:38:39

标签: c# winforms data-binding

我有一个表单,其中控件通过绑定源绑定到一个简单的DTO。一个特定的控件是下拉列表,绑定是:

this.cboCustomer.DataBindings.Add(new Binding("SelectedValue", this.bindingSource, "CustomerId", true, DataSourceUpdateMode.OnPropertyChanged));
this.cboCustomer.DataBindings.Add(new Binding("Text", this.bindingSource, "CustomerName", true, DataSourceUpdateMode.OnPropertyChanged));

它有2个绑定,因为我更新了对象的2个属性。

我也有一个活动:

private void cboCustomer_SelectedIndexChanged(object sender, EventArgs e)
{
    var customer= cboCustomer.SelectedItem as Customer;
    if (customer == null)
        return;

    myObject.AccountNumber = customer.AccountNumber;
}

我输入所有相关信息并保存实体。保存后,我将bindingsource的数据源设置为一个新实例,即:

bindingSource.DataSource = myObject = new MyObject();

但是,在第一次之后,当我从下拉列表中选择一个项目时,即使列表中有项目,SelectedItem属性也始终为空。

我必须点击其他控件,在那里输入内容,然后显示下拉列表中的选项。

我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

这是WinForms绑定中的典型问题。要处理它,您可以在任何需要重置绑定的地方使用以下模式:

private MyObject myObject;

// gets or sets the currently bound object
public MyObject MyObject
{
    get
    {
        return myObject;
    }
    set
    {
        myObject = value;

        myObjectBindingSource.RaiseListChangedEvents = false;
        myObjectBindingSource.EndEdit();

        // rebind
        myObjectBindingSource.DataSource = null;
        myObjectBindingSource.DataSource = myObject;

        myObjectBindingSource.RaiseListChangedEvents = true;
        myObjectBindingSource.ResetBindings(false);
    }
}

然后,而不是

bindingSource.DataSource = myObject = new MyObject();

只需设置新属性:

MyObject = new MyObject();

答案 1 :(得分:0)

问题是控件上的2个绑定。删除了对Text属性的绑定,现在组合框的行为符合预期。