Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get First Visible Item in WPF ListView C#

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.

like image 423
Kirk Ouimet Avatar asked May 28 '10 04:05

Kirk Ouimet


1 Answers

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;
    }
like image 132
Kirk Ouimet Avatar answered Sep 19 '22 19:09

Kirk Ouimet