Single click edit in WPF DataGrid

Austin picture Austin · Aug 6, 2010 · Viewed 70.8k times · Source

I want the user to be able to put the cell into editing mode and highlight the row the cell is contained in with a single click. By default, this is double click.

How do I override or implement this?

Answer

Micael Bergeron picture Micael Bergeron · Aug 13, 2010

Here is how I resolved this issue:

<DataGrid DataGridCell.Selected="DataGridCell_Selected" 
          ItemsSource="{Binding Source={StaticResource itemView}}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Nom" Binding="{Binding Path=Name}"/>
        <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}"/>
    </DataGrid.Columns>
</DataGrid>

This DataGrid is bound to a CollectionViewSource (Containing dummy Person objects).

The magic happens there : DataGridCell.Selected="DataGridCell_Selected".

I simply hook the Selected Event of the DataGrid cell, and call BeginEdit() on the DataGrid.

Here is the code behind for the event handler :

private void DataGridCell_Selected(object sender, RoutedEventArgs e)
{
    // Lookup for the source to be DataGridCell
    if (e.OriginalSource.GetType() == typeof(DataGridCell))
    {
        // Starts the Edit on the row;
        DataGrid grd = (DataGrid)sender;
        grd.BeginEdit(e);
    }
}