数据绑定到列表-在ListBox,ComboBox中查看数据源的更改 [英] Databinding to List - See changes of data source in ListBox, ComboBox
问题描述
我希望在删除对象或将对象添加到列表中作为DataSource
时将ListBox
自动显示更改.
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
中,如果您想查看绑定列表控件中数据源的更改,例如ComboBox
,ListBox
或DataGridView
(复杂的双向数据绑定),您应该使用实现 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
应该实现
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是否可以解决双向数据绑定问题?
如果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-我应该使用List<T>
.如何使用List<T>
解决问题?
Note 3 - I should use List<T>
. How can I solve the problem using List<T>
?
如果必须使用List<T>
,则可以在需要时重置列表框的数据绑定,例如,每次更改后,都应将其DataSource
分配为null,然后再次将其分配给数据列表:
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;
这篇关于数据绑定到列表-在ListBox,ComboBox中查看数据源的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!