The problem with the code is with the CurrentCell property binding. it binds the new current cell before NewRowCommand is called.
Lets assume you where on "Name" column on the last row, so what happens is:
- You press the enter key.
- Current cell is updated with the new cell. (Age)
- Then your command is called, and uses the the new current cell(Age) and therefore adds new row.
I would suggest keeping a reference to the previous cell upon currentcell update. and using it instead of currentCell.
public DataGridCellInfo SelectedCell
{
get
{
return _selectedCell;
}
set
{
_lastCell = _selectedCell; //here is my edit
_selectedCell = value;
OnPropertyChanged("SelectedCell");
}
}
So the new NewRow(object obj) looks like this:
private void NewRow(object obj)
{
if (SelectedRow == People.Last())
{
if (SelectedConfirmation == "Add New")
{
if (_lastCell.Column !=null && _lastCell.Column.Header.ToString() =="Age")//here is my edit
{
People.Add(new Person());
}
}
}
}
Also there is a problem inside DataGrid_CellGotFocus(object sender, RoutedEventArgs e). take a look at my edit, i dropped the row.IsSelected assinment.
private void DataGrid_CellGotFocus(object sender, RoutedEventArgs e)
{
// Lookup for the source to be DataGridCell
if (e.OriginalSource.GetType() == typeof(DataGridCell))
{
// Starts the Edit on the row;
DataGrid grd = (DataGrid)sender;
grd.BeginEdit(e);
Control control = GetFirstChildByType<Control>(e.OriginalSource as DataGridCell);
if (control != null)
{
control.Focus();
}
DataGridCell cell = GetDataGridCell(grd.CurrentCell);
DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
if (dataGrid != null)
{
if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
{
if (!cell.IsSelected)
cell.IsSelected = true;
}
}
}
}
I ran the edited code on my pc, it works great! let me know if there are any issues I might have missed.