WPF: DataGrid And The Return Key
Comments available as RSS 2.0
A decent DataGrid is really the only thing WPF doesn’t have. The WPF Toolkit DataGrid is a great addition but it’s still lacking in a few places.
To me, it would seem natural for the Tab key to move to the next column and Enter to move to the next row, but there isn’t really support for this.
After experimenting with KeyUp and KeyDown events, I came up with the following method, based on a similar technique by Vincent Sibal. It makes the DataGrid more usable in my opinion.
/// <summary> /// Focuses the next row when enter or return is pressed /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Microsoft.Windows.Controls.DataGridRowEditEndingEventArgs"/> instance containing the event data.</param> private void dgResources_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) { if(e.EditAction == DataGridEditAction.Commit && dgResources.SelectionUnit == DataGridSelectionUnit.Cell) { if(Keyboard.IsKeyDown(Key.Enter) || Keyboard.IsKeyDown(Key.Return)) { // get the row and column indexes of the currently selected cell int currentColIndex = dgResources.Columns.IndexOf(dgResources.CurrentColumn), currentRowIndex = dgResources.Items.IndexOf(e.Row.Item); var rowToSelect = dgResources.Items[currentRowIndex + 1]; // get the next row var colToSelect = dgResources.Columns[currentColIndex]; int rowIndex = dgResources.Items.IndexOf(rowToSelect); // select the new cell dgResources.SelectedCells.Clear(); dgResources.SelectedCells.Add(new DataGridCellInfo(rowToSelect, colToSelect)); this.Dispatcher.BeginInvoke(new DispatcherOperationCallback((param) => { // get the new cell, set focus, then open for edit var cell = DataGridUtils.GetCell(dgResources, rowIndex, currentColIndex); cell.Focus(); dgResources.BeginEdit(); return null; }), DispatcherPriority.Background, new object[] { null }); } } }
I also found it difficult to select a control when a Cell enters edit mode, but after vastly overthinking the problem used the Initialized event of the TextBox in the CellEditingTemplate:
/// <summary> /// Focuses and selects all text in the TextBox used for editing when it is selected. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void txt_Initialized(object sender, EventArgs e) { TextBox tb = sender as TextBox; if(tb != null) { tb.Focus(); tb.SelectAll(); } }

Comments
Leave a Comment