我有一个在 XAML 中声明的按钮,它具有 MouseDown 和 MouseUp 属性,它们都调用指定的方法...
<Button x:Name="btnBackward" Content="Backward"
MouseDown="btnBackward_MouseDown"
MouseUp="btnBackward_MouseReleased" Width="50" Height="25"
Margin="65,400,377,45"/>
但是,方法 btnBackward_MouseReleased 从未被调用。
private void btnBackward_MouseReleased(object sender,
System.Windows.Input.MouseEventArgs e)
{
Console.WriteLine("mousereleased");
this.isRewinding = false;
}
我错过了什么?
您应该在此处使用预览事件
。因此,挂接到 PreviewMouseDown
和 PreviewMouseUp
而不是 MouseDown
和 MouseUp
。
<Button x:Name="btnBackward" Content="Backward"
PreviewMouseDown="btnBackward_MouseDown"
PreviewMouseUp="btnBackward_MouseReleased"/>
原因表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.
但是,如果您右键单击您的按钮 MouseUp
和 MouseDown
事件将完美运行,因为在这种情况下点击不会耗尽事件并且它们会正确冒泡上。