Search code examples
c#wpflistviewobservablecollection

Limit number of displayed items in WPF ListView


So I have a ListView control backed by an ObservableCollection<> which periodically gets items added to it. However I would only like to display at most the first 10 items; i.e. if there are at most 10 items it displays them all, while resizing accordingly, and if there are more than 10 it stops displaying them at the 10th item.

I was wondering if there was a reasonable way to do this as my current intuition is to have a second collection which mirrors the top 10 items of the ItemsSource, updating accordingly.


Solution

  • You could do something like this (i haven't tested it, but you may get the idea):

    _defaultView = CollectionViewSource.GetDefaultView(YourCollection);
    _defaultView.SortDescriptions.Add(new System.ComponentModel.SortDescription(".", System.ComponentModel.ListSortDirection.Ascending));
    _defaultView.Filter = o =>
    {
        int index = YourCollection.OrderBy(s => s).ToList().IndexOf(o as string);
        return index >= 0 && index < 10;
    };
    _defaultView.Refresh();