Move Focus to Next Cell on Enter Key Press in WPF DataGrid?
A much simpler implementation. The idea is to capture the keydown event and if the key is "Enter", then move to the next tab which is next cell of the grid.
/// <summary>
/// On Enter Key, it tabs to into next cell.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataGrid_OnPreviewKeyDown(object sender, KeyEventArgs e)
{
var uiElement = e.OriginalSource as UIElement;
if (e.Key == Key.Enter && uiElement != null)
{
e.Handled = true;
uiElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
How about this solution? Cancel the action of the Enter key by setting Handled=true
and press the Tab key.
public Constructor()
{
InitializeComponent();
this.SampleDataGrid.PreviewKeyDown += MoveCellOnEnterKey;
}
private void MoveCellOnEnterKey(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter)
{
// Cancel [Enter] key event.
e.Handled = true;
// Press [Tab] key programatically.
var tabKeyEvent = new KeyEventArgs(
e.KeyboardDevice, e.InputSource, e.Timestamp, Key.Tab);
tabKeyEvent.RoutedEvent = Keyboard.KeyDownEvent;
InputManager.Current.ProcessInput(tabKeyEvent);
}
}
private void dg_PreviewKeyDown(object sender, KeyEventArgs e)
{
try
{
if (e.Key == Key.Enter)
{
e.Handled = true;
var cell = GetCell(dgIssuance, dgIssuance.Items.Count - 1, 2);
if (cell != null)
{
cell.IsSelected = true;
cell.Focus();
dg.BeginEdit();
}
}
}
catch (Exception ex)
{
MessageBox(ex.Message, "Error", MessageType.Error);
}
}
public static DataGridCell GetCell(DataGrid dg, int row, int column)
{
var rowContainer = GetRow(dg, row);
if (rowContainer != null)
{
var presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
if (presenter != null)
{
// try to get the cell but it may possibly be virtualized
var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
if (cell == null)
{
// now try to bring into view and retreive the cell
dg.ScrollIntoView(rowContainer, dg.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
}
return null;
}