WPF DataGrid-获取鼠标光标所在的行号 [英] WPF DataGrid - get row number which mouse cursor is on

查看:200
本文介绍了WPF DataGrid-获取鼠标光标所在的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在DataGrid中鼠标光标所在的行号(因此基本上是在MouseEnter事件上),所以我也可以获得与ItemSource绑定在一起的DataGridRow项,

I am looking to get the row number of which the mouse cursor is on in a DataGrid (So basically on a MouseEnter event) so I can get the DataGridRow item of which the ItemSource is binded too,

我为MouseEvent使用的XAML是...

The XAML I have for the MouseEvent is...

   <DataGridTextColumn.ElementStyle>
      <Style TargetType="{x:Type TextBlock}">
         <EventSetter Event="MouseEnter" Handler="Event"></EventSetter>
         <Setter Property="ToolTip" Value="{Binding Property}" />
      </Style>
   </DataGridTextColumn.ElementStyle>

事件本身...

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

也许我做这件事是不可能的,但我会如果无法以某种方式做到这一点感到惊讶。

Maybe it isnt possible the way I am doing it, but I'd be surprised if it can't be done some way.

谢谢

推荐答案

如果您访问 DataGridRow 对象上,然后可以使用 DataGridRow.GetIndex 方法

If you access the DataGridRow object that your mouse is over, then you can find its row index using the DataGridRow.GetIndex method:

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

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

The GetParentOfType method is actually an extension method that I use:

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

这篇关于WPF DataGrid-获取鼠标光标所在的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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