I implemented my own CollectionView to bind a data collection to a DataGrid in WPF.
The main goal is pagination, which works quite well. I wrote the following C # code:
public class SchemesCollectionView : CollectionView { private readonly IList<Scheme> innerList; private readonly int itemsPerPage; private int currentPage = 1; public SchemesCollectionView(IList<Scheme> source, int itemsPerPage) : base(source) { innerList = source; this.itemsPerPage = itemsPerPage; } public override int Count { get { return itemsPerPage; } } public int CurrentPage { get { return currentPage; } set { currentPage = value; OnPropertyChanged(new PropertyChangedEventArgs("CurrentPage")); OnPropertyChanged(new PropertyChangedEventArgs("FirstItemNumber")); OnPropertyChanged(new PropertyChangedEventArgs("LastItemNumber")); } } public int ItemsPerPage { get { return this.itemsPerPage; } } public int PageCount { get { return (this.innerList.Count() + this.itemsPerPage - 1) / this.itemsPerPage; } } public int LastItemNumber { get { var end = currentPage * itemsPerPage - 1; end = (end > innerList.Count()) ? innerList.Count() : end; return end + 1; } } public int StartIndex { get { return (currentPage - 1) * itemsPerPage; } } public int FirstItemNumber { get { return ((currentPage - 1) * itemsPerPage) + 1; } } public override object GetItemAt(int index) { var offset = index % (ItemsPerPage); var position = StartIndex + offset; if (position >= innerList.Count) { position = innerList.Count - 1; } return innerList[position]; } public void MoveToNextPage() { if (CurrentPage < PageCount) { CurrentPage += 1; } Refresh(); } public void MoveToPreviousPage() { if (CurrentPage > 1) { CurrentPage -= 1; } Refresh(); } public void MoveToFirstPage() { CurrentPage = 1; Refresh(); } public void MoveToLastPage() { CurrentPage = PageCount; Refresh(); } }
As already mentioned, pagination works very well. But I can not do filtering and sorting. When I add my own filter to the Filter property, it is completely ignored. Same thing with sorting. I see arrows on the column headers after I clicked them, but different sorting is not reflected in the DataGrid.
What am I missing here? Hope someone can help.
source share