Home > Mobile >  ListView Filter limit items with CollectionView
ListView Filter limit items with CollectionView

Time:11-24

I have a ObservableCollection and I want to display only 10 items of it in the ListView. How must the Filter look like?

CollectionView altView = (CollectionView)CollectionViewSource.GetDefaultView(alteParkingListe.ItemsSource);
altView.Filter  = //Show only 10 Items

CodePudding user response:

The signature of the the Filter property is as follows:

public virtual Predicate<object> Filter { get; set; }

Consequently, you need to supply a Predicate<object> which is a funtion that takes an argument of type object and returns a bool. The argument passed in is an item of the underlying collection. The filter predicate is called for each item. The return value indicates whether the item is preserved (true) or filtered out (false) of the view.

As you can see, the filter does not know anything about the underlying collection itself, only each item individually. Hence, there is no direct way of doing this with a filter.

Of course you can do dirty tricks like keeping the count of filtered items like this:

var itemsCount = 0;
altView.Filter = obj =>   itemsCount <= 10;

However, this is not a good solution and you need to ensure that itemsCount is reset each time.


Now for what you should do instead: Simply create another collection property and assign a filtered variant of your main collection, no collection view and no dirty tricks involved. Filtering can be done using Linq's Take method:

FilteredItemsCollection = AllItemsCollection.Take(10);
  • Related