Question

I have a dataGrid in a wpf application that use the MVVM pattern.

The dataGrid can sort the row if I click in the column name and I can order by many columns if I use the shift key. So the control gives all I need.

However, I notice that when I have sorted the rows and I add a new element, the new element is really add as last element in my observable collection in my view model, but in the dataGrid is show in the position that this element has according to the sort criterion.

So in my view model I try to select the new element. I get the index of the last element of my observalbeCollection, but then this select the incorrect element in the DataGrid, the last element shown, but this is not my new element.

In this post it seems that one solution is to use a CollectionViewSource, but if I am not wrong, in this case I need to implement in my view model all the code to sort elements, so is more code when the dataGrid does this work.

This makes me ask which has really the responsibility to sort the elements? the view model or the view? Because if I implent the sort in my view model, the view model needs to know that exists a datagrid that is clicked in some column name and the sort the elements. I think that sort the elements is something visual, so the view model does not need to do that work, but perhaps I am wrong.

How could I solve this problem?

Was it helpful?

Solution

When I put data into any collection control in WPF (using MVVM), I always bind to the collection ItemsSource property as well as the SelectedItem or SelectedItems properties, depending on the SelectionMode of the control.

This enables me to find out which item(s) is/are selected and to choose whichever (data) item I want to be selected from the view model.

If the order that the user sets in the DataGrid is important, then I would perform the sorting from the view model, but if it is only important to the user while they work, then you can simply ignore the order... remember, you can access the selected item through the bound SelectedItem property in your view model.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top