以编程方式WPF DataGrid行双击事件 [英] WPF DataGrid row double click event programmatically

查看:924
本文介绍了以编程方式WPF DataGrid行双击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式创建一个DataGrid,并需要添加一个双击行事件。在C#中怎么做?我发现这个;

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);

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

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

推荐答案

你可以在XAML中在DataGridRow的资源部分添加默认样式,并在其上声明事件设置器

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

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

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"/>

并在代码中:

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
  }

这篇关于以编程方式WPF DataGrid行双击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆