是否有数据网格鼠标按下命中测试以获取点击的行和列索引?

时间:2016-12-30 10:18:28

标签: wpf datagrid wpfdatagrid hittest

使用Winforms'DataGridView,可以使用HitTest来确定鼠标按下的列和行索引(以及其他事件)。

Dim hti As DataGridView.HitTestInfo = sender.HitTest(e.X, e.Y)

与WPF DataGrid有类似之处吗?我需要获取MouseLeftButtonDown事件的行和列索引。

2 个答案:

答案 0 :(得分:0)

它比这更复杂,但以下链接应该有助于获取行和列的索引。

WPF DataGrid - 检测已点击的列,单元格和行: http://blog.scottlogic.com/2008/12/02/wpf-datagrid-detecting-clicked-cell-and-row.html

WPF DataGrid - get row number which mouse cursor is on

如上所述,您必须使用VisualTreeHelper类遍历构成DataGrid的Visual元素。

答案 1 :(得分:-1)

对于那些可能希望避免我在这里搜索的人来说,我总是困惑的总代码是能够提供的:

  1. 当前行索引
  2. 当前列索引
  3. 当前列标题和
  4. 能够公开行上列的值。

    代码进入MouseLeftButtonup事件,DGrid1是网格的名称

    Dim currentRowIndex As Integer = -1
    Dim CurrentColumnIndex As Integer = -1
    Dim CurrentColumnHeader As String = ""
    Dim Myrow As DataRowView = Nothing
    Dim dep As DependencyObject = DirectCast(e.OriginalSource, DependencyObject)
    While dep IsNot Nothing And Not TypeOf dep Is DataGridCell And Not TypeOf dep Is Primitives.DataGridColumnHeader
        dep = VisualTreeHelper.GetParent(dep)
        If dep IsNot Nothing Then
            If TypeOf dep Is DataGridCell Then
                Dim cell As DataGridCell = DirectCast(dep, DataGridCell)
                Dim col As DataGridBoundColumn = DirectCast(cell.Column, DataGridBoundColumn)
                Myrow = DGrid1.SelectedItem
                CurrentColumnHeader = col.Header.ToString
                CurrentColumnIndex = col.DisplayIndex
                currentRowIndex = DGrid1.Items.IndexOf(DGrid1.CurrentItem)
                Exit While
            End If
        End If
    End While
    If currentRowIndex = -1 OrElse CurrentColumnIndex = -1 OrElse CurrentColumnHeader = "" OrElse Myrow Is Nothing Then Exit Sub
    
         'code to consume the variables from here
    
    Dim strinwar As String = Myrow.Item("header name or index").ToString()