简体   繁体   English

WPF:我如何处理ListBox项目的点击?

[英]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. 在我的WPF应用程序中,我正在处理ListBox SelectionChanged事件,它运行正常。

Now I need to handle a click event (even for the already selected item); 现在我需要处理一个点击事件(即使对于已经选择的项目); I've tried MouseDown but it does not work. 我尝试过MouseDown,但它不起作用。 How can I handle a ListBox click on an item? 如何处理ListBox单击项目?

Just handle PreviewMouseDown event: 只需处理PreviewMouseDown事件:

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

Perhaps try the PreviewMouseDown event. 也许尝试PreviewMouseDown事件。 The MouseDown event gets swallowed and converted to the SelectionChanged event. 吞下MouseDown事件并将其转换为SelectionChanged事件。

Only downside is that the PreviewMouseDown will occur before the SelectionChanged . 唯一的缺点是PreviewMouseDown将在SelectionChanged之前发生。

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

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

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

Let me know if this helps... 如果这有帮助,请告诉我......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我想在winforms列表框控件中检测项目双击。 [如何处理点击空白区域?] - i want to detect an item double click in a winforms listbox control. [how to handle click on blank area?] 如何单击一个按钮,该按钮将从ListBox中删除一个项目,而该列表中包含C#中ListBox的信息? - How do I click a button that will remove an item from a ListBox and the List that holds the information for the ListBox in C#? 如何在WPF中的数据绑定菜单中处理单击事件 - How do I handle click events in a data bound menu in WPF 如何处理WPF中多个类似按钮上的单击事件? - How do I handle click events on multiple similar buttons in WPF? WPF:如何处理按钮内的Listview上的鼠标单击? - WPF: How do I handle mouse click on a Listview inside of a Button? 如何右键单击列表框中的项目并在WPF上打开菜单 - how to right click on item from Listbox and open menu on WPF 如何使用WPF和MVVM模式将控件绑定到列表框中的选定项目? - How do I bind controls to the selected item in a listbox using WPF and the MVVM pattern? 使用WPF在列表框项上移动+单击功能 - shift +click functionality on listbox item using WPF 具有ContextMenu单击事件的WPF ListBox项 - WPF ListBox item with ContextMenu click event 在 wpf xaml 中单击获取列表框项目的名称 - get name of listbox item on click in wpf xaml
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM