views:

302

answers:

3

Anyone know how to get a ListViewItem by grabbing the first visible item in the ListView? I know how to get the item at index 0, but not the first visible one.

+1  A: 

I can't believe there isn't an easier way...

http://social.msdn.microsoft.com/forums/en-US/wpf/thread/2d527831-43aa-4fd5-8b7b-08cb5c4ed1db

BFree
Oh my God I think I just threw up in my mouth. What about using the VisualTreeHelper to HitTest the child at the relative point 0,0?
Josh Einstein
Used HitTest to get it to work. Thanks for the suggestion!
Kirk
A: 

This was so painful to get working:

HitTestResult hitTest = VisualTreeHelper.HitTest(SoundListView, new Point(5, 5));
System.Windows.Controls.ListViewItem item = GetListViewItemFromEvent(null, hitTest.VisualHit) as System.Windows.Controls.ListViewItem;

And the function to get the list item:

System.Windows.Controls.ListViewItem GetListViewItemFromEvent(object sender, object originalSource)
    {
        DependencyObject depObj = originalSource as DependencyObject;
        if (depObj != null)
        {
            // go up the visual hierarchy until we find the list view item the click came from  
            // the click might have been on the grid or column headers so we need to cater for this  
            DependencyObject current = depObj;
            while (current != null && current != SoundListView)
            {
                System.Windows.Controls.ListViewItem ListViewItem = current as System.Windows.Controls.ListViewItem;
                if (ListViewItem != null)
                {
                    return ListViewItem;
                }
                current = VisualTreeHelper.GetParent(current);
            }
        }

        return null;
    }
Kirk
A: 

Thanks! That was just what I was looking for!

Dvora