8

I am using a WPF ListView with an always visible vertical scrollbar. I have a MouseLeftButtonUp event handler on the ListView. The handler is working properly except when the vertical scrollbar is clicked when it has nothing to do i.e. the ListView box doesn't have enough items to do any scrolling.

In that case nothing should happen as the user has clicked on the vertical scrollbar just to make sure there are no items just off the screen. However the ListView fires the MouseLeftButtonUp event. If the vertical scrollbar does have some work to do the event does not get fired.

Here is my simplifiewd XAML

<ListView MouseLeftButtonUp="DoSomething_MouseLeftButtonUp" SelectionMode="Single" ScrollViewer.VerticalScrollBarVisibility="Visible">
  <ListView.View>
    <GridView>
      <GridViewColumn Width="170" Header="Venue" DisplayMemberBinding="{Binding Path=Venue}" />
    </GridView>
  </ListView.View>
</ListView>

Is there anyway to prevent the MouseLeftButtonUp event firing when the vertical scroll bar is clicked irespective of whether the scroll bar has any work to do or not?

sipsorcery
  • 30,273
  • 24
  • 104
  • 155

3 Answers3

8

Neither of the other answers worked in my case because of complex styling in the ListBoxItem. This did however:

var item = ItemsControl.ContainerFromElement(sender as ItemsControl, (DependencyObject)e.OriginalSource) as ListBoxItem;
if (item != null)
{
    // Handle it
}
Jackson Pope
  • 14,520
  • 6
  • 56
  • 80
  • This works for me too. Other answers won't work due to the other controls in the list box. Thanks – superstar Jun 07 '17 at 19:21
  • If you used MVVM and `PassEventArgsToCommand="True"` the solution above also work, you just need to replace sender by `e.Source` (e beeing RoutedEventArgs) – Sebastien Servouze Jun 04 '19 at 09:14
4

This is similar to this question, and the answer is the same. In your MouseLeftButtonUp handler, check the MouseButtonEventArgs.OriginalSource property. That will tell you where the click originated.

Community
  • 1
  • 1
Charlie
  • 15,069
  • 3
  • 64
  • 70
  • In my own GridView, I have many columns containing an image, textblocks, textblocks with Runs... am I supposed to check for all those? – Dave Haynes Feb 15 '10 at 02:32
2

For ListBox I've used the following code:

 if (e.OriginalSource is TextBlock || e.OriginalSource is Border)
 {
     // do your stuff
 }
Aleksandr
  • 339
  • 3
  • 6