连接列表< T>到ListBox并查看ListBox中数据源的更改 [英] Connect List<T> to a ListBox and see changes of data source in ListBox

查看:222
本文介绍了连接列表< T>到ListBox并查看ListBox中数据源的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望当我删除或添加一个对象到列表中时, 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.

如何将列表< T> 连接到 ListBox 并立即查看 ListBox 中的底层列表的更改?

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

推荐答案

Windows窗体中,在您想要查看绑定列表控件中数据源更改的情况下,如 ComboBox ListBox DataGridView (复杂的双向数据绑定),你应该使用一个实现 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是否解决双向数据绑定Probelm?

在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> 它不解决双向数据绑定问题。您需要通知控件以从绑定源重新加载数据,因此您可以调用 BindingSource ResetBindings 方法。这样,绑定控件将从数据源重新加载数据并显示最新数据:

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 - 我应该使用列表< T> code>。如何使用列表< T> ?解决问题?

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

如果您必须使用列表< 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;

这篇关于连接列表&lt; T&gt;到ListBox并查看ListBox中数据源的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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