Hou*_*man 10 .net c# sorting wpf datagrid
我相信大多数人现在都会惊讶为什么我们必须关闭wpf数据网格的虚拟化.虽然虚拟化确实有助于减少内存占用,但它会增加CPU开销并且滚动体验并非完美无瑕.
根据我们客户的要求,我们必须禁用数据网格中的虚拟化并进一步优化它,现在它可以非常平滑地上下滚动而没有任何延迟.缺点是数据被预加载并保存在存储器中.这是我们可以忍受的解决方案.
然而,排序现在已成为一个大问题.虽然使用CustomSorter:IComparer确实是比通常的SortDecriptors更好的排序替代品,但是在我们的情况下它几乎没有任何区别,尽管整个行都在重绘.
有没有办法提高非虚拟化数据网格的排序速度?
非常感谢,
更新:
我遇到了一个想法,我正在尝试实施.取消绑定Itemssource,进行排序,一旦排序完成,重新绑定Itemssource.
为了实现这一点,我从DataGrid派生来捕获SortHandler(即用户点击列时)
public class CustomSortDataGrid : DataGrid
{
public CustomSortDataGrid()
{
Sorting += SortHandler;
}
private void SortHandler(object sender, DataGridSortingEventArgs e)
{
DataGridColumn column = e.Column;
IComparer comparer = null;
// prevent the built-in sort from sorting
e.Handled = true;
ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;
//set the sort order on the column
column.SortDirection = direction;
//use a ListCollectionView to do the sort.
var lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(ItemsSource);
comparer = new BidYieldComparer(direction);
//apply the sort
lcv.CustomSort = comparer;
}
}
Run Code Online (Sandbox Code Playgroud)
这将使用优于SortDescriptors的更快的Comparer Sorting.现在问题是在哪个阶段我解除项目排序,应用排序,等待排序,一旦事件(哪一个?)触发,然后将Itemssource重新绑定到视图.
BindingOperations.ClearBinding(this, ItemsSourceProperty);
Run Code Online (Sandbox Code Playgroud)
上面的这一行将清除绑定.
//apply the sort
lcv.CustomSort = comparer;
Run Code Online (Sandbox Code Playgroud)
理论上(不确定这是否正确)ItemsSource = lcv; 会重新绑定它.但表现仍然相同.:(
任何想法的人?
首先尝试对集合进行排序,然后将排序后的集合绑定到 DataGrid。排序操作的速度取决于您将使用的排序算法。我曾经使用插入排序算法,您可以在http://en.wikipedia.org/wiki/Insertion_sort中阅读有关该算法的信息。我很快就会给你发一个例子。
更新
你可以在这里VB.Net找到实现
你可以在这里C#找到实现