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

Xap*_*ann 33 c# wpf datagrid

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

myRow.MouseDoubleClick += new RoutedEventHandler(Row_DoubleClick);
Run Code Online (Sandbox Code Playgroud)

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

Roh*_*ats 73

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

<DataGrid>
    <DataGrid.Resources>
        <Style TargetType="DataGridRow">
            <EventSetter Event="MouseDoubleClick" Handler="Row_DoubleClick"/>
        </Style>
    </DataGrid.Resources>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

要么

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

<DataGrid x:Name="dataGrid"/>
Run Code Online (Sandbox Code Playgroud)

并在代码后面:

Style rowStyle = new Style(typeof(DataGridRow));
rowStyle.Setters.Add(new EventSetter(DataGridRow.MouseDoubleClickEvent,
                         new MouseButtonEventHandler(Row_DoubleClick)));
dataGrid.RowStyle = rowStyle;
Run Code Online (Sandbox Code Playgroud)

有事件处理程序的例子:

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