WPF DataGrid Pagination

2019-02-25 13:03发布

问题:

I am using the example provided here StackOverflow related question, if i have an even number of items in the grid then it works all good, but if for instance i have an odd number like 7 items, it throws a out of range exception which I fixed by adding this line

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];
}

The problem is that after fixing this, if you set the items per page to 2 then you will have 4 pages, the first 3 pages look right but the last one repeats the last item twice. like this

I am new to WPF and i am not sure how i can handle this piece, i do not understand why it would repeat the item.

回答1:

The issue is not with GetItemAt method, leave it as it was:

    public override object GetItemAt(int index)
    {
        var offset = index % (this._itemsPerPage); 

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

The problem is with Count property override. In case it is the last page it should return the correct items left:

    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; 
        }
    }