持续从DataGrid排序到ItemsSource集合 [英] Persist sorting from DataGrid to ItemsSource collection

查看:164
本文介绍了持续从DataGrid排序到ItemsSource集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DataGrid ,我正在尝试做最直接的排序方法:点击每一列的标题。

I have a DataGrid and I'm trying to do the Sort thing the most straightforward way: by clicking on the header of each column.

这对于视图(在MVVM上下文 )中非常有用,但是我想对底层的ViewModel集合进行排序( ObservableCollection )也。关于如何实现源集合的任何建议?

This is working great on the View (in the MVVM context), but I want to sort the underlying ViewModel collection (ObservableCollection) too. Any suggestions on how to implement the source collection?

推荐答案

将网格绑定到一个 ListCollectionView ,初始化为 ObservableCollection 。网格将使用您预先创建的 ICollectionView ,而不是根据您的创建自己的 ICollectionView ObservableCollection< T> (这是默认行为),并对您的实例应用任何排序功能/谓词。

Bind the grid to a ListCollectionView, initialised with the ObservableCollection. The grid will use your pre-created ICollectionView instead of creating it's own ICollectionView based on your ObservableCollection<T> (which is the default behaviour), and apply any sorting functionality/predicates to your instance.

作为一个额外的好处,当您从ViewModel调用MyListCollectionView.Refresh()时,排序/过滤 ListCollectionView 将反映在您的网格中。

As an added benefit, sorting/filtering that ListCollectionView will be reflected in your grid whenever you call MyListCollectionView.Refresh() from your ViewModel.

完成此操作后,迭代ListCollectionView的Items集合将准确反映网格的当前过滤器/排序状态。

Once you've done this, iterating through the Items collection of your ListCollectionView will accurately reflect the current filter/sort state of your grid.

这篇关于持续从DataGrid排序到ItemsSource集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆