2010/08/31

WPF: Get the item in the ListView under the mouse cursor.

How to get the item in the ListView under the mouse cursor. These codes are gethered at CodeProject here.

// A ListView control named lv. Let’s do something in MouseDoubleClick event handler.
private void
lv_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
    int index = GetCurrentIndex(e.GetPosition); 
    MyClass instance = lvUsers.Items[index] as MyClass
    // Now you got the original object and then do what you want. 
}
delegate Point GetPositionDelegate(IInputElement element);
private int GetCurrentIndex(GetPositionDelegate getPosition) {
    int index = -1;
    for (int i = 0; I < lv.Items.Count; i++) {
        ListViewItem item = GetListViewItem(i);
        if (item == null)
            continue;
        if (IsMouseOverTarget(item, getPosition)) {
            index = i;
            break;
        }
    }
    return index;
}
private ListViewItem GetListViewItem(int index) {
    if (lv.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
    return null;
    return lv.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;
}
private bool IsMouseOverTarget(Visual target, GetPositionDelegate getPosition) {
    Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
    Point mousePos = getPosition((IInputElement)target); 
    return bounds.Contains(mousePos);
}

2 comments:

Anonymous said...

Nice helpfull code snippet, thanks much

Anonymous said...

Snippet helped me a lot for my Drag and Drop implementation in a ListView! Thank you very much!