【问题标题】:How to paginate an ObservableCollection?如何对 ObservableCollection 进行分页?
【发布时间】:2008-12-01 03:44:55
【问题描述】:

我有一个 ListBox,其中包含太多项目,并且 UI 越来越慢(虚拟化已开启等)。所以我在考虑只显示前 20 个项目并允许用户浏览结果集(即 ObservableCollection)。

有人知道 ObservableCollection 是否存在分页机制吗?以前有人做过吗?

谢谢!

【问题讨论】:

    标签: wpf pagination observablecollection paginator


    【解决方案1】:

    这个工具在 ObservableColleton 基类中不能直接使用。您可以扩展 ObservableCollection 并创建执行此操作的自定义 Collection。您需要将原始 Collection 隐藏在这个新类中,并基于 FromIndex 和 ToIndex 动态地将项目范围添加到类中。覆盖 InsertItem 和 RemoveItem。我在下面给出一个未经测试的版本。但请把它当作伪代码。

     //This class represents a single Page collection, but have the entire items available in the originalCollection
    public class PaginatedObservableCollection : ObservableCollection<object>
    {
        private ObservableCollection<object> 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);
        }
    }
    

    更新:我在这里有一篇关于此主题的博文 - http://jobijoy.blogspot.com/2008/12/paginated-observablecollection.html,源代码已上传到 Codeplex

    【讨论】:

    • 这是个好主意。我喜欢这个概念,但我们在内存中复制对象,不是吗?
    • 不,我们没有复制对象。假设如果有 10 页,每页有 10 个项目。 originalCollection 将有 100 个项目,而我们仅将 10 个项目引用到此 Paginatedcollection。
    猜你喜欢
    • 2011-11-09
    • 2021-04-15
    • 2011-12-01
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多