WPF如何处理自定义集合的CollectionChanged事件? [英] How does WPF handle CollectionChanged events for custom collections?

查看:517
本文介绍了WPF如何处理自定义集合的CollectionChanged事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些定制类来包装/表示要用于WPF数据绑定的集合。我可以确定的最低要求是该类需要实现 IEnumerable INotifyCollectionChanged

I have a few custom classes that wrap/represent collections which I want to use for WPF data-binding. The minimum requirement I could determine was that the class needs to implement IEnumerable and INotifyCollectionChanged.

NotifyCollectionChangedEventArgs 组合起来引发 CollectionChanged 事件时,我想知道如何用于 newIndex oldIndex ,因为我的班级不支持 IList 并且没有索引功能。

While putting together the NotifyCollectionChangedEventArgs for raising the CollectionChanged event, I was wondering what to use for newIndex and oldIndex since my class doesn't support IList and has no indexing capabilities.

这使我想到了一个问题:

That brought me to my question:

如果类没有实施 IList ,在侦听 CollectionChanged 时WPF框架会忽略该操作,并始终以该操作为重置?如果没有,他们将如何做( newIndex 和/或 oldIndex 应该使用什么?)

If the classes do not implement IList, will the WPF framework when listening to CollectionChanged ignore the action and always react as if the action was Reset? If not, how do they do it (and what should I use for newIndex and/or oldIndex)?

推荐答案

答案是WPF会听 CollectionChanged 并相应地采取行动没有实现 IList 接口。 WPF会将数据集合映射到其视图,并且视图始终创建 IndexedEnumerable 包装器,以确保它可以通过索引访问集合。因此,如果将集合绑定到WPF实现的依赖项属性,如 ItemsControl.ItemsSource ,则无需实现 IList 允许 INotifyCollectionChanged 工作。但是,如果将集合绑定到自己的属性,而不是直接使用源,则应使用 CollectionViewSource 创建视图。

The answer is WPF will listening to CollectionChanged and act accordingly even the collection didn't implement IList interface. WPF will map data collection to its view(s), and a view always create a IndexedEnumerable wrapper to ensure that it can access the collection through an index. So, if you bind a collection to a WPF implemented dependency property like ItemsControl.ItemsSource, you don't need to implement IList to let INotifyCollectionChanged work. But if you bind a collection to you own property, instead of using the source directly, you should create a view by using CollectionViewSource.

这篇关于WPF如何处理自定义集合的CollectionChanged事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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