How to get Item under cursor in ListView ?
如何在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
实际上我需要在WinForms.NET中使用类似GetItemAt(int x,int y)的方法
Thanks!
谢谢!
UPD: Answer was found. Watch extension method below
UPD:找到答案。观看下面的扩展方法
2 个解决方案
#1
13
You can try using the VisualTreeHelper.HitTest method. Something like this:
您可以尝试使用VisualTreeHelper.HitTest方法。像这样的东西:
System.Windows.Point pt = e.GetPosition(this);
System.Windows.Media.VisualTreeHelper.HitTest(this, pt);
#2
12
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;
}
#1
13
You can try using the VisualTreeHelper.HitTest method. Something like this:
您可以尝试使用VisualTreeHelper.HitTest方法。像这样的东西:
System.Windows.Point pt = e.GetPosition(this);
System.Windows.Media.VisualTreeHelper.HitTest(this, pt);
#2
12
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;
}