问题
I have a DataGrid in my view, and I would like to select a row. In my view model I have a property to bind the SelectedIndex of the dataGrid.
When I add a new row to the dataGrid, this element is add at the end of the elements, show in the dataGrid I can see it in the last position.
However, if i have shorted the elements in the dataGrid because I click in a column name and this filter makes that the new element it will be in the first position of the dataGrid, then I select the incorrect element, because internally the position of the new element is in the N position, not the first.
For example. I have a table that has the name and username of people. I get some persons in the dataGrid and I short them by name. now I insert a new person whose name is AAAA. When I add the new person, in the dataGrid I can se this person in the first row, but I select the last person because in my view model I select the index of my new person, that internally is add at the end.
How can I select in the datagrid the correct row when I have a used a filter?
Thanks.
回答1:
you could use an ICollectionView to handle your SelectedItem
this._myView= CollectionViewSource.GetDefaultView(this.MySourceCollection);
...
this._myView.MoveCurrentTo(newitemwithAAAA);
then your new element is selected
来源:https://stackoverflow.com/questions/17743904/how-to-get-the-correct-index-in-a-datgrid-when-i-use-the-mvvm-pattern-and-i-have