如何对ObservableCollection进行分页?

时间:2008-12-01 03:44:56

标签: wpf pagination observablecollection paginator

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

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

谢谢!

1 个答案:

答案 0 :(得分:4)

此工具不能直接在ObservableCollecton基类中使用。您可以扩展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