[英]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.