WPF DataGrid - 获取鼠标光标所在的行号

use*_*422 4 c# wpf datagrid

我想在DataGrid中获取鼠标光标所在的行号(所以基本上是在MouseEnter事件上)所以我可以得到ItemSource绑定的DataGridRow项,

我对MouseEvent的XAML是......

   <DataGridTextColumn.ElementStyle>
      <Style TargetType="{x:Type TextBlock}">
         <EventSetter Event="MouseEnter" Handler="Event"></EventSetter>
         <Setter Property="ToolTip" Value="{Binding Property}" />
      </Style>
   </DataGridTextColumn.ElementStyle>
Run Code Online (Sandbox Code Playgroud)

活动本身......

  private void Event(object sender, MouseEventArgs e)
  {   
     // I have the DataGrid object itself.
     m_DataGrid.?
  }
Run Code Online (Sandbox Code Playgroud)

也许它不可能像我这样做,但如果不能以某种方式做到,我会感到惊讶.

谢谢

She*_*dan 9

如果访问DataGridRow鼠标所在的对象,则可以使用以下DataGridRow.GetIndex方法查找其行索引:

private void Event(object sender, MouseEventArgs e)
{
    HitTestResult hitTestResult = 
        VisualTreeHelper.HitTest(m_DataGrid, e.GetPosition(m_DataGrid));
    DataGridRow dataGridRow = hitTestResult.VisualHit.GetParentOfType<DataGridRow>();
    int index = dataGridRow.GetIndex();
}
Run Code Online (Sandbox Code Playgroud)

GetParentOfType方法实际上是我使用的扩展方法:

public static T GetParentOfType<T>(this DependencyObject element) where T : DependencyObject
{
    Type type = typeof(T);
    if (element == null) return null;
    DependencyObject parent = VisualTreeHelper.GetParent(element);
    if (parent == null && ((FrameworkElement)element).Parent is DependencyObject) parent = ((FrameworkElement)element).Parent;
    if (parent == null) return null;
    else if (parent.GetType() == type || parent.GetType().IsSubclassOf(type)) return parent as T;
    return GetParentOfType<T>(parent);
}
Run Code Online (Sandbox Code Playgroud)


use*_*422 1

好吧,我在这里找到了答案......

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

不要被文章标题所迷惑..

对于我的解决方案,我基本上使用了

private void MouseOverEvent(object sender, MouseEventArgs e)
{
        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;

            // navigate further up the tree
            while ((dep != null) && !(dep is DataGridRow))
            {
               dep = VisualTreeHelper.GetParent(dep);
            }

            DataGridRow row = dep as DataGridRow;

           //!!!!!!!!!!!!!* (Look below) !!!!!!!!!!!!!!!!!

         }
Run Code Online (Sandbox Code Playgroud)
    • 现在您可以使用 row.Item 获取自己的对象,宾果,它位于正确的行索引上

因此,所有关于使用鼠标原始源并向上查看 VisualTree 直到找到正确的元素。