【问题标题】:Update ComboBox Dropdown After BindingSource is Changed更改 BindingSource 后更新 ComboBox 下拉列表
【发布时间】:2015-08-29 04:42:00
【问题描述】:

我在网上浏览了一堆示例,但找不到任何可行的方法(或者我做错了)。

ComboBox 像这样绑定到 (String, String) 和 Nothing 的字典:

cbBox.DataSource = New BindingSource(dictStrings.Keys, Nothing)

但是,在调用dictStrings.Add(s1, s2) 之后,ComboBox 的下拉菜单不会列出新添加到dictStrings 的值。我怎样才能解决这个问题?我尝试重新绑定datasource,但它只是将下拉菜单留空。我尝试使用ResetBindings() 函数,但效果不佳。谢谢。

【问题讨论】:

  • 使用List<T> 作为数据源也存在同样的问题——它们不会监视内容的变化或提供通知。您可以使用BindingList<T> 代替列表,但对于字典,您需要编写一个自定义集合类,可能实现 IDictionary 并提供通知。 ObservableCollection(Of KeyValuePair(Of String, String)) 可能有效(尚未尝试)
  • 我检查了一下,从 IDictionary 和 INotifyCollectionChanged 构建的 ObservableDictionary 很酷,但它无助于解决这个问题 - 它需要 IBindingList,而以 Dictionary 为基础并不容易实现。

标签: vb.net combobox


【解决方案1】:

您可以创建一个新绑定,但您会丢失当前的索引位置,并且如果您连接了 SelectedIndexChanged 事件,这可能会引发一些意想不到的烟花,因此这是一种解决方法:

Dim index As Integer = cbBox.SelectedIndex
RemoveHandler cbBox.SelectedIndexChanged, AddressOf cbBox_SelectedIndexChanged
dictStrings.Add("new key", "new value")
cbBox.DataSource = New BindingSource(dictStrings.Keys, Nothing)
cbBox.SelectedIndex = index
AddHandler cbBox.SelectedIndexChanged, AddressOf cbBox_SelectedIndexChanged

【讨论】:

    【解决方案2】:

    你试过 cbBox.DataSource.refresh 吗?

    【讨论】:

    • 我明白了:找不到类型“BindingSource”上的公共成员“刷新”
    • 没有这种方法。
    【解决方案3】:
    ComboBox1.Update()
    

    应该解决问题。

    编辑:cbBox.Update()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 2011-02-26
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多