简体   繁体   English

DataSource更改时,ComboBox不会自动更新?

[英]ComboBox doesn't automatically update when DataSource changes?

For some reason when adding or remove items from the DataSource (a simple BindingList) the ComboBox updates accordingly but if I edit an item like this, it doesn't update automatically: 出于某种原因,当从DataSource(一个简单的BindingList)添加或删除项目时,ComboBox会相应地更新,但如果我编辑这样的项目,它不会自动更新:

myBindingList[index].Name = "NewName";
myBindingList[index].Value = newValue;

In order to get it to update when I edit an item as opposed to creating or removing an item I have to do this after the change is made: 为了在编辑项目时更新它而不是创建或删除项目,我必须在更改后执行此操作:

myComboBox.DataSource = null;
myComboBox.DataSource = myBindingList;

This fixes the problem but it seems like a rather messy solution. 这解决了问题,但它似乎是一个相当混乱的解决方案。 Also with large lists it may become slow (premature optimization I know) but still is there a way to force the ComboBox to update without completely re-assigning its DataSource? 对于大型列表,它可能会变慢(我知道的过早优化),但仍然有办法强制ComboBox更新而不完全重新分配其DataSource?

Thanks for reading. 谢谢阅读。

this is stated in the MSDN forums: 这在MSDN论坛中说明:

The IBindingList interface contains the ListChanged event where controls like the combobox hook up into if the underlying datasource assigned to it implements the said interface. IBindingList接口包含ListChanged事件,其中如果分配给它的基础数据源实现所述接口,则组合框之类的控件将挂钩。 your datasource must raise the corresponding ListChanged with proper ListChangeEventArgs if ever you add, remove, change, etc. your IBindingList implementor. 如果你添加,删除,更改等你的IBindingList实现者,你的数据源必须用适当的ListChangeEventArgs引发相应的ListChanged。 this way, whenever the underlying source you used to bind to your combobox is changed, the corresponding UI control (combobox) is refreshed. 这样,只要更改了用于绑定到组合框的基础源,就会刷新相应的UI控件(组合框)。

you say you are using BindingList and in fact you do get the combobox to reflect add or remove items events. 你说你正在使用BindingList,实际上你确实得到了组合框以反映添加或删除项目事件。 I think you should do the update of the items already inside your BindingList in another way because looks like the proper BindingList events are not firing. 我认为你应该以另一种方式更新BindingList中已有的项目,因为看起来像正确的BindingList事件没有被触发。

you could either investigate into that or simply live with reset and reassign the DataSource, I don't think is too bad, you are in Statefull Windows Forms application not in SatetLess Webforms so you do have your objects there all the time :) 你可以调查那个或只是生活重置并重新分配DataSource,我不认为太糟糕,你在Statefull Windows窗体应用程序而不是在SatetLess Webforms中所以你一直有你的对象:)

You need observable collections and IPropertyChange implementation: 您需要可观察的集合和IPropertyChange实现:

ComboBox bound to a ObservableCollection does not update 绑定到ObservableCollection的ComboBox不会更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM