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

时间:2014-04-01 15:24:46

标签: c# wpf datagrid

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

myRow.MouseDoubleClick += new RoutedEventHandler(Row_DoubleClick);

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

1 个答案:

答案 0 :(得分:67)

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

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

如果想在后面的代码中执行此操作。在网格上设置x:Name,以编程方式创建样式并将样式设置为RowStyle。

<DataGrid x:Name="dataGrid"/>

并在代码背后:

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
  }