Skip to content

Clicking or DoubleClicking on an Item in a ListView

This is little more than a pointer to a fantastic post by Mike over at Mike’s Code Blog, but I figured it was worth passing along. Mike’s post is focused on finding which item was double clicked, while mine is on determining when the double clicking happened on an item at all.

 I’ve recently come up against a problem in which we were attaching a doubleclick event to our listview, only to discover it fires when we did something like click on the scrollbar quickly. Since we only wanted it to fire when we were double clicking on the listview item, we had to come up with some way of figuring out where in the listview the user had clicked.

Mike’s code made it easy… I’m reproducing our permutation of it here:

First, we put our event pointer in the XAML like so:

<ListView MouseDoubleClick=”ListViewDoubleClick”>

Then we put this in the code behind:

protected void ListView_MouseDoubleClick(object sender, RoutedEventArgs e)
{
    
//grab the original element that was doubleclicked on and search from child to parent until
    //you find either a ListViewItem or the top of the tree

    DependencyObject originalSource = (DependencyObject)e.OriginalSource;
   
while ((originalSource != null) && !(originalSource is ListViewItem)) 
     {
          originalSource =
VisualTreeHelper.GetParent(originalSource); 
     }
       //if it didn’t find a ListViewItem anywhere in the hierarch, it’s because the user
      //didn’t click on one. Therefore, if the variable isn’t null, run the code

      if (originalSource != null)
     
{
         //code here
      }
}
 

That’s it!