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

对着背影说爱祢 提交于 2019-11-30 00:49:55

问题


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?


回答1:


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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/6938752/wpf-how-do-i-handle-a-click-on-a-listbox-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!