Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid row double click event programmatically

Tags:

c#

wpf

datagrid

I need to programmatically create a DataGrid and need to add a double click row event to it. How is this done in C#? I found this;

myRow.MouseDoubleClick += new RoutedEventHandler(Row_DoubleClick); 

Although this does not work for me since I am binding the DataGrid.ItemsSource to a collection and not manually adding in the rows.

like image 664
Xaphann Avatar asked Apr 01 '14 15:04

Xaphann


1 Answers

You can do that in XAML by adding default style for DataGridRow under its resources section and declare event setter over there:

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

OR

In case want to do it in code behind. Set x:Name on grid, create style programatically and set the style as RowStyle.

<DataGrid x:Name="dataGrid"/> 

and in code behind:

Style rowStyle = new Style(typeof(DataGridRow)); rowStyle.Setters.Add(new EventSetter(DataGridRow.MouseDoubleClickEvent,                          new MouseButtonEventHandler(Row_DoubleClick))); dataGrid.RowStyle = rowStyle; 

AND

There is example of event handler:

  private void Row_DoubleClick(object sender, MouseButtonEventArgs e)   {      DataGridRow row = sender as DataGridRow;      // Some operations with this row   } 
like image 158
Rohit Vats Avatar answered Sep 24 '22 06:09

Rohit Vats