C#关于List<T>作为数据源绑定到WPF列表控件(如ListView、ListBox等),数据源更新后控件界面不能自动更新的问题。

C#中,List<T>作为数据源绑定到WPF列表控件(如ListView、ListBox等),数据源更新后控件界面却不能自动更新。

解决方案:用 BindingList<T> 或者 ObservableCollection<T> 代替 List<T>。

一、这个问题的本质:

List<T> 没有实现 INotifyCollectionChanged 接口,而不是 INotifyPropertyChanged 接口,准确的说是两个接口都没实现。所以即使在 List<T> 属性中人工加上了 INotifyPropertyChanged 接口的实现(如:NotifyPropertyChanged方法),也没有效果。

二、两个替代方法(BindingList<T>、ObservableCollection<T>)的异同之处:

这两个类均支持双向绑定(作为WPF控件数据源),但都没有排序功能,也就是没有 List<T> 中的 Sort 方法。

BindingList<T> ---- System.ComponentModel

ObservableCollection<T> ---- System.Collections.ObjectModel

这两个类,即使使用自动属性,不实现INotifyPropertyChanged接口;只要集合改变(项目加减),就能自动实现数据的更新。但是对于集合内项目自身属性的改变(项目内的属性变化),还是需要实现实现INotifyPropertyChanged接口才能自动更新。

【微软推荐WPF集合控件使用 ObservableCollection<T> 作为控件数据源】

三、参考文献

《BindingList<T>类》

https://learn.microsoft.com/zh-cn/dotnet/api/system.componentmodel.bindinglist-1?view=net-7.0

《ObservableCollection<T>类》

https://learn.microsoft.com/zh-cn/dotnet/api/system.collections.objectmodel.observablecollection-1?view=net-7.0

另:

Stackoverflow上说:

To be short, ObservableCollection does not listen to changes in its children but only to Insert and Remove events.

On the other side BindingList does listen to changes and updates raised by its children. But because Binding list must listen to all its children

但是实际测试中并没有测出来。

https://stackoverflow.com/questions/455284/observablecollectionof-t-vs-bindinglistof-t

posted @ 2023-02-03 15:13  syzcyyx  阅读(597)  评论(0编辑  收藏  举报