我已经实现了自己的 CollectionView 来将数据集合绑定到 WPF 中的 DataGrid。
主要目标是分页,它工作得很好。我编写了以下 C# 代码:
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();
}
}
如前所述,分页效果很好。但我无法进行过滤和排序工作。当我将自定义过滤器添加到 Filter 属性时,它会被完全忽略。排序也是一样。单击它们后,我可以在列标题上看到箭头,但不同的排序不会反映在 DataGrid 中。
我在这里缺少什么?希望有人可以提供帮助。