18

In my WPF app I'm handling a ListBox SelectionChanged event and it runs fine.

Now I need to handle a click event (even for the already selected item); I've tried MouseDown but it does not work. How can I handle a ListBox click on an item?

Arcturus
  • 26,677
  • 10
  • 92
  • 107
Cris
  • 12,124
  • 27
  • 92
  • 159

3 Answers3

37

Just handle PreviewMouseDown event:

private void listBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    var item = ItemsControl.ContainerFromElement(listBox, e.OriginalSource as DependencyObject) as ListBoxItem;
    if (item != null)
    {
        // ListBox item clicked - do some cool things here
    }
}
Vitus
  • 511
  • 4
  • 11
7

Perhaps try the PreviewMouseDown event. The MouseDown event gets swallowed and converted to the SelectionChanged event.

Only downside is that the PreviewMouseDown will occur before the SelectionChanged.

Arcturus
  • 26,677
  • 10
  • 92
  • 107
4

Listbox internally uses the mouse down to perform selection changed. So you can use preview mouse down event.

Apart from preview mouse down, you can use EventManager.RegisterClassHandler...

     EventManager.RegisterClassHandler(typeof(ListBoxItem), ListBoxItem.MouseLeftButtonDownEvent, new RoutedEventHandler(EventBasedMouseLeftButtonHandler));

     private static void EventBasedMouseLeftButtonHandler(object sender, RoutedEventArgs e)
     {
     }

Let me know if this helps...

WPF-it
  • 19,625
  • 8
  • 55
  • 71