Problem with DataGrid Rows in WPF
-
I have a datagrid where I have two buttons on each row - one for moving a row up and one for moving a row down. Each button has a command for allowing the user to move the selected row in either direction. The problem that I am facing is that it not working. I think the problem that I may have is that the other controls (combo boxes) on the rows are bound to data sources through the MVVM model where I am manipulating the rows on the code behind of the XAML thinking this would be the logical place in which to do it. The code I have for one of the buttons is below: private void MoveRowDown(object sender, ExecutedRoutedEventArgs e) { int currentRowIndex = dg1.ItemContainerGenerator.IndexFromContainer(dg1.ItemContainerGenerator.ContainerFromItem(dg1.SelectedItem)); if (currentRowIndex >= 0) { this.GetRow(currentRowIndex + 1).IsSelected = true; } } private DataGridRow GetRow(int index) { DataGridRow row = (DataGridRow)dg1.ItemContainerGenerator.ContainerFromIndex(index); if (row == null) { dg1.UpdateLayout(); dg1.ScrollIntoView(selectedAttributes.Items[index]); row = (DataGridRow)dg1.ItemContainerGenerator.ContainerFromIndex(index); } return row; }
-
I have a datagrid where I have two buttons on each row - one for moving a row up and one for moving a row down. Each button has a command for allowing the user to move the selected row in either direction. The problem that I am facing is that it not working. I think the problem that I may have is that the other controls (combo boxes) on the rows are bound to data sources through the MVVM model where I am manipulating the rows on the code behind of the XAML thinking this would be the logical place in which to do it. The code I have for one of the buttons is below: private void MoveRowDown(object sender, ExecutedRoutedEventArgs e) { int currentRowIndex = dg1.ItemContainerGenerator.IndexFromContainer(dg1.ItemContainerGenerator.ContainerFromItem(dg1.SelectedItem)); if (currentRowIndex >= 0) { this.GetRow(currentRowIndex + 1).IsSelected = true; } } private DataGridRow GetRow(int index) { DataGridRow row = (DataGridRow)dg1.ItemContainerGenerator.ContainerFromIndex(index); if (row == null) { dg1.UpdateLayout(); dg1.ScrollIntoView(selectedAttributes.Items[index]); row = (DataGridRow)dg1.ItemContainerGenerator.ContainerFromIndex(index); } return row; }
Instead of working with the grid you should work with the data. Add a sort field to the class used to populate the grid and manipulate the order in the VM.
Never underestimate the power of human stupidity RAH