How to paginate an ObservableCollection?

前端 未结 1 1724
-上瘾入骨i
-上瘾入骨i 2021-01-03 06:26

I have a ListBox with way too many items in it and the UI is getting slower and slower (virtualization is on, etc). So I was thinking about displaying only the first 20 item

1条回答
  •  不知归路
    2021-01-03 07:01

    This facility is not directly available in the base ObservableCollecton class. You can extend the ObservableCollection and create a custom Collection which does this. You need to hide the original Collection inside this new class and based on a FromIndex and ToIndex give dynamically add the range of items to the class. Override InsertItem and RemoveItem. I am giving a not-tested version bellow. But please take this as just pseudo code.

     //This class represents a single Page collection, but have the entire items available in the originalCollection
    public class PaginatedObservableCollection : ObservableCollection
    {
        private ObservableCollection originalCollection;
    
        public int CurrentPage { get; set; }
        public int CountPerPage { get; set; }
    
        protected override void InsertItem(int index, object item)
        {
            //Check if the Index is with in the current Page then add to the collection as bellow. And add to the originalCollection also
            base.InsertItem(index, item);
        }
    
        protected override void RemoveItem(int index)
        {
            //Check if the Index is with in the current Page range then remove from the collection as bellow. And remove from the originalCollection also
            base.RemoveItem(index);
        }
    }
    
    
    

    UPDATE: I have a blog post about this topic on here - http://jobijoy.blogspot.com/2008/12/paginated-observablecollection.html and the source code is uploaded to Codeplex.

    0 讨论(0)
    提交回复
    热议问题