如何在WPF ListView中获取鼠标下的项目

12

如何在ListView中获取鼠标下的项目?

例如,当我移动鼠标光标时,我希望能够获取其下的项目并将其名称放入状态栏中。

实际上,我需要像WinForms.NET中的GetItemAt(int x,int y)方法一样的方法。

谢谢!

更新:已找到答案。请查看下面的扩展方法。

2个回答

17
你可以尝试使用VisualTreeHelper.HitTest方法。类似这样:
    System.Windows.Point pt = e.GetPosition(this);
    System.Windows.Media.VisualTreeHelper.HitTest(this, pt);

谢谢!使用您的代码,我制作了一个小扩展方法。希望有人会发现它有用。 - Grigory

16
public static object GetObjectAtPoint<ItemContainer>(this ItemsControl control, Point p)
where ItemContainer : DependencyObject
{
    // ItemContainer - can be ListViewItem, or TreeViewItem and so on(depends on control)
    ItemContainer obj = GetContainerAtPoint<ItemContainer>(control, p);
    if (obj == null)
        return null;

    return control.ItemContainerGenerator.ItemFromContainer(obj);
}

public static ItemContainer GetContainerAtPoint<ItemContainer>(this ItemsControl control, Point p)
where ItemContainer : DependencyObject
{
    HitTestResult result = VisualTreeHelper.HitTest(control, p);
    DependencyObject obj = result.VisualHit;

    while (VisualTreeHelper.GetParent(obj) != null && !(obj is ItemContainer))
    {
        obj = VisualTreeHelper.GetParent(obj);
    }

    // Will return null if not found
    return obj as ItemContainer; 
}

嗨Grigory,帮帮忙,我想做和你一样的事情,但是当我粘贴你的两个函数时,我遇到了这个错误:“扩展方法必须在非泛型中定义”。 - YMELS
2
嗨,阅读一些有关C#中扩展方法的文章或书籍。基础知识非常重要。如果需要更多内容-您必须将此方法放入静态类中。 - Grigory
1
@YMELS 不要在泛型类中声明扩展方法。 - Billy Jake O'Connor
该扩展方法期望点相对于容器(ListView等)本身的右上角。如果您从鼠标事件处理程序中获取坐标,请注意您需要手动计算偏移量。 - Daniel Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接