You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BindingSource更新时ComboBox选中项始终设为索引1的问题解决

问题:WinForms共享BindingList时ComboBox选中状态异常

我在两个UserControl之间共享BindingSource,其中一个控件负责管理数据源(添加项),另一个控件将数据源中的项关联到对象属性:

  • 第一个控件:包含绑定到BindingList(Of Variable)的BindingSource的ListBox,以及添加新项的按钮,这部分功能正常。
  • 第二个控件:ComboBox的项绑定到同一BindingList(Of Variable)的BindingSource,但通过第一个控件向BindingSource添加项时,第二个控件的ComboBox选中项总会变为索引1对应的项。我需要保留ComboBox的选中状态,后续还计划在同一控件中使用多个ComboBox,每个选择同一基础列表中的不同项。

第一个控件代码

Private bs As BindingSource
Private bl As BindingList(Of Variable)

Public Overloads Sub Show(variables As BindingList(Of Variable))
    bl = variables
    bs = New BindingSource(bl, Nothing)

    'Bindings
    LbVariables.DisplayMember = "Identifiant"
    LbVariables.DataSource = bs

    Dim bd As New Binding("Visible", LbVariables, "SelectedIndex", True, DataSourceUpdateMode.OnPropertyChanged)
    AddHandler bd.Format, AddressOf LbVariables_Format
    PanelVariable.DataBindings.Add(bd)

End Sub

Private Sub LbVariables_Format(sender As Object, cevent As ConvertEventArgs)
    'LbVariables.SelectedIndex >= 0
    cevent.Value = cevent.Value >= 0
End Sub

Private Sub BtAdd_Click(sender As Object, e As EventArgs) Handles BtAdd.Click
    Dim v As New Variable("var" & i)
    bl.Add(v)
End Sub

第二个控件代码

Private bs As BindingSource
Private bl As BindingList(Of Variable)

Public Sub SetData(v As ParaVariable, variables As BindingList(Of Variable))
    'in 1st
    CbVariable.DataBindings.Clear()

    bl = variables
    bs = New BindingSource(bl, Nothing)

    'Bindings
    CbVariable.DisplayMember = "Identifiant"
    CbVariable.ValueMember = "Identifiant"
    CbVariable.DataSource = bs      

    CbVariable.DataBindings.Add(New Binding("SelectedValue", v, "IdVariable"))
End Sub

补充说明

  • ParaVariable的IdVariable属性(字符串类型)实现了INotifyPropertyChanged
  • Variable类包含名为Identifiant的字符串属性,需将其保存到v.IdVariable(与ComboBox选中项对应)
  • 两个控件的Show(...)和SetData(...)方法传入的variables是同一对象
  • 尝试过共享BindingSource而非BindingList,但问题依旧
  • 使用环境:.NET Framework 4.8 + WinForms

编辑:问题已解决
找到问题根源:ComboBox存在额外绑定——一个复选框的Visible属性与ComboBox的SelectedIndex做了绑定(逻辑类似第一个控件中LbVariables和PanelVariable的绑定)。我之前误解了DataSourceUpdateMode.OnPropertyChanged的作用,也不知道存在ControlUpdateMode属性:当复选框可见性变化时,ComboBox的选中项会被强制设置为bool转int后的0或1。将该绑定的DataSourceUpdateMode改为Never后,问题彻底解决。

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 17:53:08