How to use mouseDown and mouseUp on <button/> [duplicate]
Asked Answered
G

1

7

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 ?

Gorgerin answered 21/8, 2013 at 17:50 Comment(1)
Look here #318788Tabor
C
14

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.

Casimiracasimire answered 21/8, 2013 at 18:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.