How to apply a Filter to a PagedCollectionView but

2019-05-05 16:59发布

问题:

I have a Silverlight application where a DataForm binds on a PagedCollectionView containing objects that implement IEditableObject. Whenever the user edits an object using the DataForm, the CollectionChanged event on the collection fires twice, first with a Remove action, then with an Add action.

This is not what I want. I simply want to edit the object in the collection without firing the CollectionChanged event.

When I try to reproduce this issue in a simple test application, it behaves as I would like (i.e. not firing the event), and I cannot figure out what causes the difference in behavior between my main application and the test application.

Does anyone know when the DataForm decides to change the collection, rather than simply editing the object? What causes this difference?

Update

These articles got me thinking about Filters and as it turns out, having a Filter applied to the PagedCollectionView makes the difference. With filter: an edit action by the user results in Remove/Add from the collection, without filter: no collection change, just editing the object.

So now the question is: why does the filter cause the Remove/Add behavior (even if the filter just 'returns true', i.e. allow all entries in the collection) and how to prevent this?

回答1:

It looks like I have finally found the answer. The solution is to not listen to the CollectionChanged event of the PagedCollectionView, but to listen to the CollectionChanged event of the PagedCollectionView.SourceCollection. In my case, this is an ObservableCollection, so it actually has a CollectionChanged event.

In order for me to figure this out, I needed to realize that the PagedCollectionView should really be thought of as a view that wraps around a collection, rather than just another type of collection that I can use. Looking at it this way, it is pretty obvious that you want to look for changes in the underlying collection, not in the view. Once you have figured it out, it's all pretty obvious really :-)