lukai lukai - 5 days ago 5
C# Question

Filtering issue with ICollectionView

ImageAlbums
is an
ICollectionView
type and
GlobalCollection.MyImageAlubms
is an
ObservableCollection<T>
type.

ImageAlbums = CollectionViewSource.GetDefaultView(GlobalCollection.MyImageAlubms);
ImageAlbums.Filter = new Predicate<object>(this.FilterImageAlbumList);


In a view I'm using ImageAlbums for showing a filtered image list. I have filtered the list using
FilterImageAlbumList
method. The problem is I have used the
GlobalCollection.MyImageAlubms
in another place. In that view I have used the GlobalCollection.MyImageAlubms directly as source but in there the list are being showed as filtered also. I am also providing the filter method here, following code represents the filter method

private bool FilterImageAlbumList(object item)
{
AlbumModel albumMoel = (AlbumModel)item;
if(LOGIC_OF_FILTERING)
{
return false;
}
return true;
}


Is there any way to filter only
ImageAlbums
without affecting the GlobalCollection. FYI - I won't deep copy the Global Collection.

Answer

Your problem is caused by these two facts:

  1. Each collection instance has only one default (instance of the) view, thus CollectionViewSource.GetDefaultView always returns the same instance for the same argument
  2. WPF binding mechanism does not bind directly to a collection, but to its default collection view

So if you set a filter on the default view, its effects are visible wherever you bind to the collection.

If you want a separate instance of an ICollectionView your best bet is to instantiate it manually. For ObservableCollection<T> a good choice is ListCollectionView. So this should resolve your problems:

ImageAlbums = new ListCollectionView(GlobalCollection.MyImageAlubms);
Comments