wpf 如何在 <button/> 上使用 mouseDown 和 mouseUp
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18364366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use mouseDown and mouseUp on <button/>
提问by Jean-Fran?ois Savard
I have a button declared in XAML which has MouseDown and MouseUp attributes that both call a specified method...
我有一个在 XAML 中声明的按钮,它具有 MouseDown 和 MouseUp 属性,它们都调用指定的方法......
<Button x:Name="btnBackward" Content="Backward"
MouseDown="btnBackward_MouseDown"
MouseUp="btnBackward_MouseReleased" Width="50" Height="25"
Margin="65,400,377,45"/>
However, the method btnBackward_MouseReleased is never called.
但是,从未调用过 btnBackward_MouseReleased 方法。
private void btnBackward_MouseReleased(object sender,
System.Windows.Input.MouseEventArgs e)
{
Console.WriteLine("mousereleased");
this.isRewinding = false;
}
What am-I missing ?
我错过了什么?
回答by Rohit Vats
You should use Preview eventshere. So, instead of MouseDownand MouseUp, hook to PreviewMouseDownand PreviewMouseUp.
你应该Preview events在这里使用。所以,而不是MouseDownand MouseUp,挂钩到PreviewMouseDownand PreviewMouseUp。
<Button x:Name="btnBackward" Content="Backward"
PreviewMouseDown="btnBackward_MouseDown"
PreviewMouseUp="btnBackward_MouseReleased"/>
Reason form MSDN-
原因形式MSDN-
Button suppresses MouseLeftButtonDown and MouseLeftButtonDown bubbling events raised by the Button or its composite elements in favor of capturing the mouse and raising a Click event that is always raised by the Button itself. The event and its data still continue along the route, but because the Button marks the event data as Handled, only handlers for the event that specifically indicated they should act in the handledEventsToo case are invoked. If other elements towards the root of your application still wanted an opportunity to handle a control-suppressed event, one alternative is to attach handlers in code with handledEventsToo specified as true. But often a simpler technique is to change the routing direction you handle to be the Preview equivalent of an input event. For instance, if a control suppresses MouseLeftButtonDown, try attaching a handler for PreviewMouseLeftButtonDown instead.
Button 抑制由 Button 或其复合元素引发的 MouseLeftButtonDown 和 MouseLeftButtonDown 冒泡事件,以支持捕获鼠标并引发始终由 Button 本身引发的 Click 事件。事件及其数据仍沿路由继续,但由于 Button 将事件数据标记为已处理,因此仅调用专门指示它们应在handledEventsToo 情况下执行的事件的处理程序。如果应用程序根目录的其他元素仍然希望有机会处理控制抑制事件,一种替代方法是在代码中附加处理程序,并将handledEventsToo 指定为true。但通常更简单的技术是将您处理的路由方向更改为输入事件的预览等效项。例如,如果控件禁止 MouseLeftButtonDown,请尝试为 PreviewMouseLeftButtonDown 附加一个处理程序。
However, if you right click on your button MouseUpand MouseDownevents will work perfectly since click doesn't eat up the event in that case and they are properly bubbled up.
但是,如果您右键单击按钮MouseUp,MouseDown事件将完美运行,因为在这种情况下单击不会耗尽事件,并且它们会正确冒泡。

