Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: how do i handle a click on a ListBox item?

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?

like image 362
Cris Avatar asked Aug 04 '11 09:08

Cris


2 Answers

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
    }
}
like image 118
Vitus Avatar answered Nov 03 '22 20:11

Vitus


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.

like image 7
Arcturus Avatar answered Nov 03 '22 21:11

Arcturus