DataGrid: Insert a Row
the DomainDataSourceView class doesn’t have an Insert method, but if you have a
reference to the bound collection that does support this method (such as an ObservableCollection) and
want to insert a new row after the currently selected row, you can use the following code
ObservableCollection<Product> collection =
productDataGrid.ItemsSource as ObservableCollection<Product>;
int insertIndex = productDataGrid.SelectedIndex + 1;
// To counter some strange behavior by the DataGrid when the
// first row is selected, but not reported as such by the
// SelectedIndex property (right after the DataGrid is populated)
if (productDataGrid.SelectedIndex == -1 && collection.Count != 0)
insertIndex = 1;
collection.Insert(insertIndex, new Product());
// Select and scroll the first cell of the new row into view and start editing
productDataGrid.SelectedIndex = insertIndex;
productDataGrid.CurrentColumn = productDataGrid.Columns[0];
productDataGrid.ScrollIntoView(productDataGrid.SelectedItem,
productDataGrid.CurrentColumn);
productDataGrid.BeginEdit();