2010-09-24 44 views
10

如何在ListView中的光标下获取项目?如何让光标在WPF ListView下的项目

例如,当我移动鼠标光标,我希望得到它下面的一个项目(光标),并将其名称到状态栏。

其实我需要WinForms.NET

感谢像话getItemAt(INT X,int y)对方法!

UPD:答案被发现。手表扩展方法如下

回答

13

您可以尝试使用VisualTreeHelper.HitTest方法。事情是这样的:

System.Windows.Point pt = e.GetPosition(this); 
    System.Windows.Media.VisualTreeHelper.HitTest(this, pt); 
+0

谢谢!使用你的代码我做了一个小扩展方法。我希望有人会发现它有用 – Grigory 2010-09-28 15:52:56

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; 
} 
+0

嗨格里戈里,请帮助,我想要做你到底做了什么,但是当我粘贴你的两个函数,我得到这个错误: “扩展方法必须定义在非泛型” – YMELS 2013-03-22 21:13:02

+2

嗨,阅读一些关于C#中的扩展方法的文章或书籍。基本面非常重要。 如果更多的是这个问题 - 你必须把这个方法放到一个静态类中。 – Grigory 2013-03-24 16:53:25