ItemsSource 上的 DataGrid 排序保留已更改
我正在使用 MVVM 方法。
我有一个名为 AllSomethingViewModel 和 AllSomethingView 的 ViewModel 和视图。视图模型包含 SomethingViewModel 和 SelectedViewModel 的列表。该视图包含一个绑定到 AllSomethingViewModel 的 SelectedVM 属性的用户控件和一个允许我选择 VM 的列表框控件。基本上,当我选择一个新的 VM 时,用户控件的 DataContext 会发生变化,因此与 SomethingViewModel 关联的视图会使用新信息进行更新。
SomethingViewModel 包含称为 ObservableCollection(DataPoints) 数据的对象列表。
我有一个绑定到数据的 DataGrid 和定义的绑定到数据成员的列。这很好用。我可以更改视图,并且该数据网格会更新,一切都很好。
我遇到的问题是,我希望当数据上下文发生变化时,应用于数据网格的任何排序都能保留下来。
在与 SomethingViewModel 关联的视图上,我可以订阅 DataContextChanged 事件,但我不确定从那里要做什么才能应用排序。
例如。我有 2 SomethingViewModel。所以在我的列表中有两个选项。当我选择第一个时,我会得到带有数据的数据网格。在数据网格中,我决定按 DateCreated 升序排序。然后我转到第二个虚拟机,数据上下文发生变化,因此网格中的数据已更新,但不再排序!
I am using an MVVM approach.
I have a ViewModel and View called AllSomethingViewModel and AllSomethingView. The View Model contains a list of SomethingViewModels and a SelectedViewModel. The View contains a usercontol bound to the AllSomethingViewModel's SelectedVM property and a listbox control that lets me select a VM. Basically when I pick a new VM the usercontrol's DataContext changes and so the view associated with SomethingViewModel updates with new information.
SomethingViewModel contains a list of objects called ObservableCollection(DataPoints) data.
I have a DataGrid bound to data and columns defined that are bound to data's members. This works fine. I can change views and this datagrid updates and everything is nice.
The issue I am running into is that I would like whatever sorting is applyed to the datagrid to persist when the datacontext changes.
On the View associated with SomethingViewModel, I can subscribe to DataContextChanged event but I'm not sure what To do from there to get the sorting to apply.
For Example. I have 2 SomethingViewModels. So in my list there are 2 options. When i pick the first one I get my datagrid with my data. In the datagrid I decide to sort by DateCreated Ascending order. Then I go to my second VM, the datacontext changes so the data in the grid is updated but it is no longer sorted!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果排序是由 DataGrid 完成的,则排序将存储在 DataGrid 用于显示其数据的 ICollectionView 中。
此处有一个在代码中设置排序的示例。希望这足以让您朝着正确的方向前进
If your sorting is done by the DataGrid then it is stored in the ICollectionView that the DataGrid uses to display its data.
There's an example of setting your sorting in code here. Hope that's enough to get you going in the right direction