仅在单击 DataGrid 行时执行 WPF MouseDoubleClick 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11674199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 04:44:26  来源:igfitidea点击:

Only execute WPF MouseDoubleClick event when DataGrid row is clicked

wpfdatagriddouble-click

提问by álvaro García

I have a DataGrid in WPF. When I double-click on a row, a query to a database should be executed.

我在 WPF 中有一个 DataGrid。当我双击一行时,应该执行对数据库的查询。

This DataGrid has horizontal and vertical scroll bars, and I notice that when I click quickly on the arrow button of one of the scroll bars, it sends the query to the database.

此 DataGrid 具有水平和垂直滚动条,我注意到当我快速单击其中一个滚动条的箭头按钮时,它会将查询发送到数据库。

The problem is that I am using the DataGrid's MouseDoubleClickevent, so the scroll bars belong the the DataGrid, and when they are double-clicked, this event is raised.

问题是我使用的是DataGrid 的MouseDoubleClick事件,所以滚动条属于DataGrid,当它们被双击时,会引发此事件。

Is there any way to execute the double click event only when I double click on a row of the DataGrid and not when I double-click on part of the scroll bars?

只有当我双击 DataGrid 的一行而不是双击滚动条的一部分时,有什么方法可以执行双击事件吗?

回答by Eirik

In your MouseDoubleClick event try doing this:

在您的 MouseDoubleClick 事件中尝试这样做:

private void DataGridMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DependencyObject src = VisualTreeHelper.GetParent((DependencyObject)e.OriginalSource);

    // Checks if the user double clicked on a row in the datagrid [ContentPresenter]
    if (src.GetType() == typeof(ContentPresenter))
    {
        // Your logic..
    }
}

回答by LPL

Yes, register the event in RowStyle.

是的,在RowStyle.

<DataGrid.RowStyle>
    <Style TargetType="{x:Type DataGridRow}">
        <EventSetter Event="PreviewMouseDoubleClick" Handler="Row_PreviewMouseDoubleClick" />
    </Style>
</DataGrid.RowStyle>