WPF DataGrid以编程方式双击行事件

我需要以编程方式创建一个DataGrid,并需要向其添加双击行事件。 这是如何在C#中完成的? 我找到了这个;

myRow.MouseDoubleClick += new RoutedEventHandler(Row_DoubleClick); 

虽然这对我不起作用,因为我将DataGrid.ItemsSource绑定到集合而不是手动添加行。

你可以在XAML中通过在其资源部分下添加DataGridRow的默认样式并在那里声明事件设置器来实现:

      

要么

如果想在代码后面做。 在网格上设置x:Name ,以编程方式创建样式并将样式设置为RowStyle。

  

并在代码后面:

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

有事件处理程序的例子:

  private void Row_DoubleClick(object sender, MouseButtonEventArgs e) { DataGridRow row = sender as DataGridRow; // Some operations with this row }