如何在ListView中的光標下獲取項目?如何讓光標在WPF ListView下的項目
例如,當我移動鼠標光標,我希望得到它下面的一個項目(光標),並將其名稱到狀態欄。
其實我需要WinForms.NET
感謝像話getItemAt(INT X,int y)對方法!
UPD:答案被發現。手錶擴展方法如下
如何在ListView中的光標下獲取項目?如何讓光標在WPF ListView下的項目
例如,當我移動鼠標光標,我希望得到它下面的一個項目(光標),並將其名稱到狀態欄。
其實我需要WinForms.NET
感謝像話getItemAt(INT X,int y)對方法!
UPD:答案被發現。手錶擴展方法如下
您可以嘗試使用VisualTreeHelper.HitTest方法。事情是這樣的:
System.Windows.Point pt = e.GetPosition(this);
System.Windows.Media.VisualTreeHelper.HitTest(this, pt);
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 2010-09-28 15:52:56