在wpf的dataGrid中按Enter鍵自動跳到下一行
PreviewKeyDown(object sender, KeyEventArgs e)
{
DataGrid grid = (DataGrid)sender;
if (e.Key == Key.Enter || e.Key == Key.Return)
{
// get the selected row
var selectedRow = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem)as DataGridRow;
// selectedRow can be null due to virtualization
if (selectedRow !=
null)
{
// there should always be a selected cell
if (grid.SelectedCells.Count !=
0)
{
// get the cell info
DataGridCellInfo currentCell = grid.SelectedCells[0];
// get the display index of the cell's column + 1 (for next column)
int columnDisplayIndex = currentCell.Column.DisplayIndex++;
// if display index is valid
if (columnDisplayIndex < grid.Columns.Count)
{
// get the DataGridColumn instance from the display index
DataGridColumn nextColumn = grid.ColumnFromDisplayIndex(columnDisplayIndex);
//
e.Handled =true;
// setting the current cell (selected, focused)
grid.CurrentCell =new DataGridCellInfo(grid.SelectedItem, nextColumn);
// tell the grid to initialize edit mode for the current cell
grid.BeginEdit();
}
}
}
}
}