WPF datagrid selected row clicked event ?

This question came up for me while looking for a solution and the answers didn't work, whether due to age or my own implementation. Either way, here is the solution that worked for me.

Add the MouseDoubleClick event to the DataGrid

        <DataGrid x:Name="DatagridMovie"
              Width="Auto"
              CanUserAddRows="False"
              CanUserDeleteRows="True"
              IsReadOnly="true"
              ItemsSource="{Binding}"
              MouseDoubleClick="Row_MouseDoubleClick">

and in the method

private void Row_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{                
    // Ensure row was clicked and not empty space
    var row = ItemsControl.ContainerFromElement((DataGrid)sender,
                                        e.OriginalSource as DependencyObject) as DataGridRow;

     if ( row == null ) return;

    … Stuff();
 }

So far I haven't noticed any problems with it. It doesn't share the problem that others have that means double clicking a header or empty space with a row selected beforehand would still cause it to run.


You could try current cell changed event handler it works only with one click and not double click if thats what your looking for, since double click can be used to for initiating editing cell or entire row or for any other process:

private void datagrid_CurrentCellChanged(object sender, EventArgs e)
    {
        int selected_index = datagrid.SelectedIndex + 1;
        // this is used for debugging and testing.
        //MessageBox.Show("The index of the row for the clicked cell is " + selected_index);

    }

you can add the event handler in the ItemContainerStyle (which is the style applied to a row) :

<DataGrid ... >
    <DataGrid.ItemContainerStyle>
        <Style TargetType="DataGridRow">
            <EventSetter Event="MouseDoubleClick" Handler="Row_DoubleClick"/>
        </Style>
    </DataGrid.ItemContainerStyle>
    ...
</DataGrid>

Then, in the handler, you can check if the row is selected

private void Row_DoubleClick(object sender, MouseButtonEventArgs e)
{
    // execute some code
}