如何对ObservableCollection进行分页?

4

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

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

谢谢!

1个回答

4

在基本的ObservableCollection类中,这个功能并不直接可用。您可以扩展ObservableCollection并创建一个自定义集合来实现这一点。您需要在这个新类中隐藏原始集合,并根据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


这是个好主意。我喜欢这个概念,但我们在内存中复制对象,对吧? - Martin
不,我们不会复制对象。假设有10页,每页有10个项目。原始集合将有100个项目,我们只引用这个分页集合中的10个项目。 - Jobi Joy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接