The DataGrid in WPF has no special event handler to handle mouse double clicks on a row. If it had, you could easily determine the row that was clicked and could gain access to the underlying data. This blog entry shows a possible solution by implementing the standard mouse event handler. In short terms it looks for the element under the mouse cursor to determine if it’s a row and in that case gets the selected element of the grid.
Let’s start by defining the DataGrid in the view:
<DataGrid x:Name="dataGrid" MouseDoubleClick="DataGrid_MouseDoubleClick"/>
The definition already contains an event handler for the double click event of the mouse. The binding of the data happens in code and is intentionally left out for brevity. In the example a simple DataSet was used. So let’s have a look at the event handler implementation:
private void DataGrid_MouseDoubleClick(object sender,
System.Windows.Input.MouseButtonEventArgs e)
{
IInputElement element = e.MouseDevice.DirectlyOver;
if(element != null && element is FrameworkElement)
{
if (((FrameworkElement)element).Parent is DataGridCell)
{
var grid = sender as DataGrid;
if (grid != null && grid.SelectedItems != null
&& grid.SelectedItems.Count == 1)
{
var rowView = grid.SelectedItem as DataRowView;
if (rowView != null)
{
DataRow row = rowView.Row;
//do something with the underlying data
}
}
}
}
}
Without having actually tried out your solution: Isn't there a problem if you quickly click one row and then another consecutively? This will be interpreted as a double click on the second row clicked although it actually isn't.
ReplyDeletehttp://stackoverflow.com/questions/3120616/wpf-datagrid-selected-row-clicked-event
ReplyDeletegives a nice solution.
That is by far the cleanest solution that I have found.
Deletei agree this is the best solution for this problem
Deleteand btw the first solution didn't work with me
how will i generate this event using MVVM
Delete