c# - 如何在 <button/> 上使用 mouseDown 和 mouseUp

标签 c# wpf xaml mouseevent mediaelement

<分区>

我有一个在 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;
}

我错过了什么?

最佳答案

您应该在此处使用预览事件。因此,挂接到 PreviewMouseDownPreviewMouseUp 而不是 MouseDownMouseUp

<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.

但是,如果您右键单击您的按钮 MouseUpMouseDown 事件将完美运行,因为在这种情况下点击不会耗尽事件并且它们会正确冒泡上。

关于c# - 如何在 <button/> 上使用 mouseDown 和 mouseUp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18364366/

相关文章:

c# - 通过 C# 使用 Windows Hello 进行 Webauthn 身份验证

c# - 使用字符串查找 C# 字典

wpf - Visual Studio 2008 : Setting the vertical separation to default in wpf designer

c# - Windows 7 任务栏进度

c# - 将小数转换为整数

c# - 找不到类型或命名空间名称,C# 初学者

c# - WPF 文本覆盖网格

.net - 如何防止 XamlWriter.Save 序列化 BaseUri 属性?

c# - 在网格中使用 2 个不同的 ViewModel

wpf - 属性名称不适用于我的数据网格列绑定(bind)