try this, i think it works, at least it worked for me.
private void dataGrid1_GotFocus(object sender, RoutedEventArgs e)
{
DependencyObject dep = (DependencyObject)e.OriginalSource;
while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
return;
if (dep is DataGridCell)
{
DataGridCell cell = dep as DataGridCell;
cell.IsSelected = true;
cell.KeyDown += new KeyEventHandler(cell_KeyDown);
}
}
void cell_KeyDown(object sender, KeyEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
if (e.Key == Key.Enter)
{
cell.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
cell.IsSelected = false;
e.Handled = true;
cell.KeyDown -= cell_KeyDown;
}
}
in this code, when the cell receives focus and the user key is down, the next cell will receive focus. Good luck helping you with this.
EDIT:
Define this function as the PreviewKeyDown datagrid event.
private void maindg_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Enter) return;
DependencyObject dep = (DependencyObject)e.OriginalSource;
while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
return;
if (dep is DataGridCell)
{
maindg.CancelEdit();
DataGridCell cell = dep as DataGridCell;
cell.IsSelected = false;
var nextCell = cell.PredictFocus(FocusNavigationDirection.Right);
if (nextCell == null)
{
DependencyObject nextRowCell;
nextRowCell = cell.PredictFocus(FocusNavigationDirection.Down);
if (nextRowCell == null) return;
while ((nextRowCell as DataGridCell).PredictFocus(FocusNavigationDirection.Left) != null)
nextRowCell = (nextRowCell as DataGridCell).PredictFocus(FocusNavigationDirection.Left);
nextCell = nextRowCell;
}
maindg.CurrentCell = new DataGridCellInfo(nextCell as DataGridCell);
(nextCell as DataGridCell).IsSelected = true;
maindg.BeginEdit();
}
e.Handled = true;
}
source
share