More DataGrid Samples: Custom Sorting, Drag and Drop of rows, Column Selection, and Single-click Editing

Jossef just wrote this great post on improving sorting in the DataGrid through a custom sort.  Check it out here.

Ben Carter also added another sample that includes row drag-and-drop and column selection through cell selection.  You can download that sample here.

One way to get single-click editing to work is to hack into one of the entry points for openning a cell/row for edit.  Cells from all DataGridColumn types can be openned for edit by pressing F2 on a selected cell, double-clicking a cell that has not been selected, typing in a selected cell, or clicking on a cell that is already selected.  An easy way to enable editing on a single-click is to catch the preview to the first mouse click of a cell and set it as selected.  Then when the DataGridCell.OnAnyMouseLeftButtonDown is called it will see that the cell has already been selected so this click will open the cell for edit.  Here is the code for it:

private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)

{

  DataGridCell cell = sender as DataGridCell;

  if (!cell.IsEditing)

  {
  // enables editing on single click

    if (!cell.IsFocused)

      cell.Focus();

    if (!cell.IsSelected)

      cell.IsSelected = true;
}

}

                                 

<Style TargetType="{x:Type dg:DataGridCell}">

   <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown" />

</Style>