代码之家  ›  专栏  ›  技术社区  ›  Ivan-Mark Debono

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

  •  0
  • Ivan-Mark Debono  · 技术社区  · 7 年前

    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 属性始终为null,即使列表中有项。

    我错过什么了吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   György Kőszeg    7 年前

    这是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();
    
        2
  •  0
  •   Ivan-Mark Debono    7 年前

    问题是控件上的2个绑定。绑定到 Text 属性被删除,组合框现在的行为与预期一致。