当数据源值改变时,WinForms组合框中的项不更新

本文关键字:更新 组合 WinForms 数据源 改变 | 更新日期: 2023-09-27 18:08:35

我有一个通过数据源绑定到List的ComboBox。由于某些原因,当数据源项更改时,组合框中的项似乎不会自动更新。我可以在调试器中看到数据源包含正确的项。

关于这个问题,StackOverflow上有很多答案,但大多数都没有答案,不适合我,或者需要从使用列表更改为BindingLists,由于使用BindingLists没有方法的代码量,我不能这样做。

当然必须有一个简单的方式只是告诉组合框刷新它的项目?我不敢相信这根本不存在。我已经有了一个事件,当Combo需要更新时触发,但是我的代码更新值没有效果。

组合声明:

    this.devicePortCombo.DataBindings.Add(
             new System.Windows.Forms.Binding("SelectedValue", 
               this.deviceManagementModelBindingSource, "SelectedDevice", true,
               DataSourceUpdateMode.OnPropertyChanged));
    this.devicePortCombo.DataSource = this.availableDevicesBindingSource;

更新组合框代码:

private void Instance_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "AvailableDevices")
    {
        // Rebind dropdown when available device list changes.
        this.Invoke((MethodInvoker)delegate
        {
            devicePortCombo.DataSource = AvailableDevicesList;
            devicePortCombo.DataBindings[0].ReadValue();
            devicePortCombo.Refresh();
        });
    }
}

当数据源值改变时,WinForms组合框中的项不更新

您没有将DataGridview的DataSource绑定到相同的BindingSource对象,在您的情况下this.availableDevicesBindingSource绑定第一次。但后来你绑定到不同的对象AvailableDevicesList。您再次使用SelectedValue的另一个绑定源,即this.deviceManagementModelBindingSource

只使用一个BindingSource,可能会解决你的问题