如何销毁或分离CollectionView [英] How to destroy or detach a CollectionView

查看:95
本文介绍了如何销毁或分离CollectionView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我观察到WPF ItemsControls的异常行为:如果将ItemsSource设置为实现 INotifyCollectionChanged 的对象,然后再设置 ItemsSource 为null,为向ItemsControl提供数据而创建的 CollectionView 仍在监听 CollectionChanged -源对象的事件。

如果现在通过另一个线程更改了源集合,则 CollectionView 会引发异常(不附加到任何控制)。
虽然我理解为什么会发生这种情况,但我确实坚持解决这种情况。

I observe an odd behaviour of WPF ItemsControls: If a set the ItemsSource to an object which implements INotifyCollectionChanged and after that set the ItemsSource to null, the CollectionView which was created to provide the data to the ItemsControl still listens to the CollectionChanged-event of the source object.
If now the source collection is changed through a different thread, the CollectionView throws an exception (without being attached to any control). While I understand why this is happening, I’m really stuck resolving this situation.

因此,主要的问题是,如何销毁 CollectionView ,使其不再监听 CollectionChanged 事件。或者,如何禁用它/分离基础集合。

Therefore the main question is, how can I destroy a CollectionView so that it does not listen any more to CollectionChanged-event. Or how can I disable it doing that / detaching the underlying collection.

请注意:所描述的行为与 ObservableCollection 。源对象是 IEnumerable 的T,并实现 INotifyCollectionChanged

Please note: The described behavior is not with ObservableCollection. The source object is an IEnumerable of T and implements INotifyCollectionChanged.

推荐答案

您正在寻找 CollectionView.DetachFromSourceCollection() 方法:

You're looking for the CollectionView.DetachFromSourceCollection() method:

var collectionView = CollectionViewSource.GetDefaultView(yourEnumerable) as CollectionView;
collectionView.DetachFromSourceCollection();

这篇关于如何销毁或分离CollectionView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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