Search code examples
wpfentity-frameworkicollectionview

Prevent ICollectionView updating filter on PropertyChanged and removing from collection


I'm experiencing an odd issue where I have a grid that's filtered, and when I modify a value on the grid, that row is removed because it no longer matches the criteria for the filter.

I am using Entity Framework to load the Local data.

mydbcontext.myobject.LoadAsync();

I am then binding the grid ItemSource to ICollectionView:

ICollectionView myitemslist = CollectionViewSource.GetDefaultView(mydbcontext.myobject.Local);

I then perform filtering on the dataset using (as an example)

BusinessProfiles.Filter = f =>
{
    var a = f as MyObjectType;
    return a.propA == a.propB;
}

That works perfectly, however if I then use the grid to modify the object such that this condition is no longer true, the object disappears from the collection.

the CollectionChanged event is firing, but I'm not expecting it to.

My understanding is that in order to behave that way, I would have to use an object that implements ICollectionViewLiveShaping such as BindingListCollectionView or ListCollectionView

When I make a change, I don't want the filter updating until after I save and propagate those changes to the DB.


Solution

  • I think your simplest solution to this is to use a separate collection to bind your view to. Filter your data using Linq at whatever point suits best. I think you'll find that this:

    ICollectionView myitemslist = CollectionViewSource.GetDefaultView(mydbcontext.myobject.Local);
    

    Is not just an ICollectionView, it's also a ListCollectionView or something similar. This applies your filter as the underlying item in the observablecollection is set. Seeing as you probably want other aspects of an observablecollection to work but you don't want filtering to kick in at this stage then do it explicitly in code and you can control precisely when what you want to happen will happen.