首页 > 解决方案 > 为什么我需要手动更新绑定的组合框?

问题描述

我的设置

我有以下(伪)EF类:

class Department {
    int ID,
    string Name
}

class DepartmentCustomer {
    int ID,
    int CustomerID,
    Customer Customer,
    string Information,
    int DepartmentID,
    Department Department
}

Class Customer {
    int ID,
    string Name,
    int? CityID,
    City City
}

Class City{
    int ID,
    string Name,
    string PostalCode
}

我有一个带有 BindingSource 的表单List(of DepartmentCustomer)和以下字段:

客户表格

城市名称的组合框具有以下属性:

ComboBoxCity.DataSource = ListOfCities  ' = List(Of City)
ComboBoxCity.ValueMember = "Id"
ComboBoxCity.DisplayMember = "Name"
ComboBoxCity.DataBindings.Add(New Binding("SelectedItem", DepartmentCustomerBindingSource, "Customer.City", True, DataSourceUpdateMode.OnPropertyChanged))

我的问题

发生时DepartmentCustomerBindingSource.CurrentItemChanged,Combobox 不同步;它有时会更新为正确的值,但是当进一步通过 BindingSource 导航时,它会保持上一个项目被选中

所以,我必须执行以下操作来手动更新组合框

Private Sub DepartmentCustomerBindingSource_CurrentItemChanged(sender As Object, e As EventArgs) Handles DepartmentCustomerBindingSource.CurrentItemChanged
    If DepartmentCustomerBindingSource.Current.Contact.City Is Nothing then
        ComboBoxCity.SelectedIndex = -1
    Else
        ComboBoxCity.SelectedItem = DepartmentCustomerBindingSource.Current.Contact.City
    End if
End Sub

(为了简单起见,我在上面的代码中省略了强制转换。这些示例类也可能没有意义 IRL)

编辑

甚至上面的代码也没有做我想要的。例如:我有两个 DepartmentCustomer 实例,一个带有 Contact.City,第二个没有 Contact.City。当表单第一次打开时,它会显示城市;当我导航到第二条记录时,组合框变为空,但是当我回到第一个组合框时,它保持为空;更令人惊讶的是,第一条记录已经更新为 Contact.City = Nothing :'(

编辑2:我自己不喜欢的解决方案

我已从组合框 ( ComboBoxCity.DataBindings.Add(New Binding("SelectedItem", DepartmentCustomerBindingSource, "Customer.City", True, DataSourceUpdateMode.OnPropertyChanged))) 中删除了数据绑定并添加了以下子

Private Sub ComboBoxCity_SelectedValueChanged(sender As Object, e As EventArgs) Handles ComboBoxCity.SelectedValueChanged
    DepartmentCustomerBindingSource.Current.Contact.City = ComboBoxCity.SelectedItem
End Sub

这行得通,但是由于我的表单中有很多这样的组合框,我认为必须有一种“自动”的方式来同步双向绑定的组合框......

编辑3:我认输

甚至我上面的“解决方案”也没有按预期工作;使用上述代码时,实例的 Contact.City 未正确更新...

我的问题

为什么我必须手动执行此操作;我错过了什么吗?我认为通过设置 DataBinding,只要导航绑定的 BindingSource,它就会更新 SelectedItem;

标签: vb.netwinformsentity-framework-6

解决方案


There seems to be an issue (bug?) with ComboBox data binding to SelectedItem property and null (Nothing) source values.

From the other side binding to SelectedValue has no such issue. So the solution/workaround is to bind to SelectedItem for updating the data soource and to SelectedValue for updating the control:

ComboBoxCity.DataBindings.Add(New Binding("SelectedItem", DepartmentCustomerBindingSource, "Customer.City", True, DataSourceUpdateMode.OnPropertyChanged))    
ComboBoxCity.DataBindings.Add(New Binding("SelectedValue", DepartmentCustomerBindingSource, "Customer.City.ID", True, DataSourceUpdateMode.Never))

推荐阅读