14

为什么当我双击滚动条或标题时会触发 DataGrid MouseDoubleClick 事件?

有什么方法可以避免这种情况并仅在我在数据网格内双击时触发事件。

4

3 回答 3

13

滚动条和标题是网格的一部分,但不处理双击,因此事件“冒泡”到网格。

不雅的解决方案是通过事件源或鼠标坐标在某种程度上找出“点击了什么”。

但你也可以做类似的事情(未经测试):

<DataGrid>
  <DataGrid.RowStyle>
    <Style TargetType="{x:Type DataGridRow}">
      <EventSetter Event="MouseDoubleClick" Handler="OnRowDoubleClicked"/>
    </Style>
  </DataGrid.RowStyle>
</DataGrid>
于 2012-04-26T08:59:12.210 回答
4

您可以在鼠标单击事件中检查有关命中点的详细信息 -

DependencyObject dep = (DependencyObject)e.OriginalSource;

// iteratively traverse the visual tree
while ((dep != null) &&
        !(dep is DataGridCell) &&
        !(dep is DataGridColumnHeader))
{
    dep = VisualTreeHelper.GetParent(dep);
}

if (dep == null)
    return;

if (dep is DataGridColumnHeader)
{
    DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
    // do something
}

if (dep is DataGridCell)
{
    DataGridCell cell = dep as DataGridCell;
    // do something
}

https://blog.scottlogic.com/2008/12/02/wpf-datagrid-detecting-clicked-cell-and-row.html

于 2012-04-26T08:45:08.350 回答
1

我遇到了同样的问题并解决了这个问题:

DependencyObject src = VisualTreeHelper.GetParent((DependencyObject)e.OriginalSource);
if (!(src is Control) && src.GetType() != typeof(System.Windows.Controls.Primitives.Thumb))
{
    //your code
}

我读过这篇文章以获得这个想法:如何检测列表视图滚动条上的双击?

我希望它会有所帮助:)

于 2016-09-21T08:40:57.617 回答