数据绑定到 List - 查看 ListBox、ComboBox 中数据源的变化 [英] Databinding to List - See changes of data source in ListBox, ComboBox

查看:17
本文介绍了数据绑定到 List - 查看 ListBox、ComboBox 中数据源的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望 ListBox 在我删除或添加一个对象到我用作它的 DataSource 的列表时自动显示更改.

I want that the ListBox automatically show changes when I remove or add an object to the list which I use as its DataSource.

如何将 List<T> 连接到 ListBox 并立即查看 ListBox 中基础列表的变化?

How can I connect a List<T> to a ListBox and see changes of underlying list in ListBox immediately?

推荐答案

Windows Forms中,想在绑定列表控件中看到数据源变化的场景,比如ComboBoxListBoxDataGridView(复杂的双向数据绑定),您应该使用实现 IBindingList 接口为 DataSource 数据绑定.最合适的实现是 BindingList<T>.这样,您的控件底层数据源中的每个添加/删除操作都将立即在控件中可见.

In Windows Forms, in a scenario that you want to see changes of data source in the bound list control, like ComboBox, ListBox or DataGridView (complex two-way data binding), you should use a class that implements IBindingList interface as DataSource of data binding. The most suitable implementation is BindingList<T>. This way each add/remove in the underlying data source of your control will be visible in the control immediately.

请记住,使用 BindingList<T> 允许绑定控件查看添加或删除的项目,但要立即查看属性更改,T 应该实现 INotifyPropertyChanged.这样,您的控件将收到 PropertyChanged 通知并始终显示最新数据.

Please keep in mind, using BindingList<T> allows the bound control see added or removed items, but to see also property changes immediately, T should implement INotifyPropertyChanged. This way your your controls will be notified of PropertyChanged and always show fresh data.

注 1 - ObservableCollection 是否解决双向数据绑定问题?

在 Windows 窗体中,一个常见的错误是使用 ObservableCollection 不适用于此要求,因为它没有实现 IBindingList.

In Windows Form, a common mistake is using ObservableCollection that will not work for this requirement since it doesn't implement IBindingList.

注 2 - BindingSource 是否解决双向数据绑定问题?

如果BindingSource 没有实现 IBindingList<T> 它没有解决双向数据绑定问题.您需要通知控件从绑定源重新加载数据,因此您可以调用 BindingSourceResetBindings 方法.这样,绑定控件将从数据源重新加载数据并显示最新数据:

If the underlying data source of BindingSource doesn't implement IBindingList<T> it doesn't solve two way data binding problem. You need to notify controls to reload data from binding source, so you can call ResetBindings method of BindingSource. This way, bound controls will reload data from data source and show the latest data:

this.bindingSource1.ResetBindings(false);

注意 3 - 我应该使用 List<T>.如何使用 List<T> 解决问题?

Note 3 - I should use List<T>. How can I solve the problem using List<T>?

如果您必须使用 List<T>,那么您可以在需要时重置列表框的数据绑定,例如在每次更改后您应该分配其 DataSource为空并再次进入数据列表:

If you must use List<T>, then you can reset the databinding of your list box when you need, for example after each change you should assign its DataSource to null and again to the list of data:

this.listBox1.DataSource = null;
this.listBox1.DataSource = list;

这篇关于数据绑定到 List - 查看 ListBox、ComboBox 中数据源的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆