Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Item under cursor in WPF ListView

Tags:

listview

wpf

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

like image 961
Grigory Avatar asked Sep 24 '10 15:09

Grigory


2 Answers

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);
like image 144
mdm20 Avatar answered Nov 11 '22 06:11

mdm20


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; 
}
like image 35
Grigory Avatar answered Nov 11 '22 06:11

Grigory