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

一个人想着一个人 提交于 2019-12-09 19:29:34

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/18364366/how-to-use-mousedown-and-mouseup-on-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!