I have a button declared in XAML which has MouseDown and MouseUp attributes that both call a specified method...
<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.
private void btnBackward_MouseReleased(object sender,
System.Windows.Input.MouseEventArgs e)
{
Console.WriteLine("mousereleased");
this.isRewinding = false;
}
What am-I missing ?
You should use Preview events
here. So, instead of MouseDown
and MouseUp
, hook to PreviewMouseDown
and PreviewMouseUp
.
<Button x:Name="btnBackward" Content="Backward"
PreviewMouseDown="btnBackward_MouseDown"
PreviewMouseUp="btnBackward_MouseReleased"/>
Reason form 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.
However, if you right click on your button MouseUp
and MouseDown
events will work perfectly since click doesn't eat up the event in that case and they are properly bubbled up.