Persist sorting from DataGrid to ItemsSource collection

隐身守侯 提交于 2020-01-06 03:25:26

问题


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.

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?


回答1:


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.

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

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



来源:https://stackoverflow.com/questions/8896422/persist-sorting-from-datagrid-to-itemssource-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!