Wpf – Only execute WPF MouseDoubleClick event when DataGrid row is clicked

datagriddouble-clickwpf

I have a DataGrid in WPF. When I double-click on a row, a query to a database should be executed.

This DataGrid has horizontal and vertical scroll bars, and I notice that when I click quickly on the arrow button of one of the scroll bars, it sends the query to the database.

The problem is that I am using the DataGrid's MouseDoubleClick event, so the scroll bars belong the the DataGrid, and when they are double-clicked, this event is raised.

Is there any way to execute the double click event only when I double click on a row of the DataGrid and not when I double-click on part of the scroll bars?

Best Answer

In your MouseDoubleClick event try doing this:

private void DataGridMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DependencyObject src = VisualTreeHelper.GetParent((DependencyObject)e.OriginalSource);

    // Checks if the user double clicked on a row in the datagrid [ContentPresenter]
    if (src.GetType() == typeof(ContentPresenter))
    {
        // Your logic..
    }
}