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

Cris picture Cris · Aug 4, 2011 · Viewed 26.5k times · Source

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?

Answer

Vitus picture Vitus · Aug 4, 2011

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
    }
}