12

How to get Item under cursor in ListView ?

For example when i move mouse cursor, i wish to get an item under it(cursor) and put its name to statusbar.

Actually i need method like GetItemAt(int x,int y) in WinForms.NET

Thanks!

UPD: Answer was found. Watch extension method below

Grigory
  • 1,911
  • 1
  • 16
  • 29

2 Answers2

17

You can try using the VisualTreeHelper.HitTest method. Something like this:

    System.Windows.Point pt = e.GetPosition(this);
    System.Windows.Media.VisualTreeHelper.HitTest(this, pt);
mdm20
  • 4,475
  • 2
  • 22
  • 24
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; 
}
Community
  • 1
  • 1
Grigory
  • 1,911
  • 1
  • 16
  • 29
  • Hi Grigory, please help, I want to do exactly what you did, but when I pasted you two functions I got this Error: "Extension method must be defined in a non-generic" – YMELS Mar 22 '13 at 21:13
  • 2
    Hi, read some articles or a book about Extension methods in C#. Fundamentals are quite important. If to be more to this issue - you have to put this method to a static class. – Grigory Mar 24 '13 at 16:53
  • 1
    @YMELS Don't declare extention methods in a generic class then. – Billy Jake O'Connor Apr 06 '18 at 13:29
  • This extension method expects the point to be relative to the top-right corner of the container (ListView, etc) itself. If you are obtaining a coordinate from a mouse event handler, note that you will need to calculate an offset manually. – Daniel Lee Jul 08 '22 at 07:10