WPF数据表格分页

3

我正在使用这里提供的示例StackOverflow相关问题,如果在网格中有偶数个项目,则一切正常,但是如果例如我有7个项目,则会抛出一个超出范围的异常,我通过添加以下行来解决此问题。

public override object GetItemAt(int index)
{
    var offset = ((index % (this._itemsPerPage)) + this.StartIndex) > this._innerList.Count - 1 ? 0 : index % (this._itemsPerPage);
    return this._innerList[this.StartIndex + offset];
}

问题在于,如果您将每页项目设置为2,则会有4个页面,前3个页面看起来正确,但最后一页会重复最后一个项目。如下所示: enter image description here 我对WPF很陌生,不确定如何处理这个问题,也不明白为什么会重复该项目。
1个回答

7
问题不在于 GetItemAt 方法,保留其原样即可:
    public override object GetItemAt(int index)
    {
        var offset = index % (this._itemsPerPage); 

        return this._innerList[this.StartIndex + offset];
    }

问题出在Count属性重载上。如果是最后一页,它应该返回正确的剩余项目数:
    public override int Count
    {
        get 
        {
            //all pages except the last
            if (CurrentPage < PageCount)
                return this._itemsPerPage;

            //last page
            int remainder = _innerList.Count % this._itemsPerPage;

            return remainder == 0 ? this._itemsPerPage : remainder; 
        }
    }

1
如果您想支持空数据集,您需要在 Count 重写的开头添加如下检查:“if (_innerList.Count == 0) return 0;”。 - Yushatak
我想实现排序,@Yushatak。但是当itemsource绑定到分页的collectionview时,默认的datagrid排序无法正常工作。 - wingskush
排序不起作用,因为public override object GetItemAt(int index)方法从单独维护的_internalList中获取项目。基类已经正确排序了项目(您可以在调试期间看到),但是PagingCollectionView没有使用这些项目。不幸的是,基类的内部列表没有受到保护,因此无法编写一个合适的子类。我觉得很奇怪,WPF没有直接支持这个功能。 - Robert F.

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