【问题标题】:MouseUp event doesnt work on left clickMouseUp 事件在左键单击时不起作用
【发布时间】:2017-02-04 20:07:29
【问题描述】:

我正在使用 Windows Presentation Foundation (WPF) 制作 GUI。当我鼠标单击一个按钮(左或右)时,我想要显示一个消息框。到目前为止,我已经设法从教程中制作了一个示例,但它仅在我右键单击时有效,而在我左键单击无效按钮。我在我的代码中看不到任何东西,这应该会阻止左键单击,所以我希望你能帮助我。

XAML 代码

<Grid>
    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="72">
        Hello, WPF!
    </TextBlock>

    <!-- This button shuld activate the even MyButton_MouseUp -->
    <Button Margin="200,250,200,20" Name="MyButton"  MouseUp="MyButton_MouseUp">
        Test
    </Button>
</Grid>

C# 代码

// This only works on right-click
private void MyButton_MouseUp(object sender, MouseButtonEventArgs e)
{
    MessageBox.Show("Hello world!");
}

【问题讨论】:

    标签: c# wpf xaml mouseup


    【解决方案1】:

    您可以订阅PreviewMouseUpTunneled 事件 而不是MouseUp

    <Button Margin="200,250,200,20" Name="MyButton"  PreviewMouseUp="MyButton_MouseUp" />
    

    PreviewMouseUp路由策略Tunneling,即它将在 VisualTree 层次结构中向下,因此 Tunnel eventsBubble events.

    【讨论】:

    • 谢谢,成功了。任何机会你也可以解释为什么? :-)
    • @Noceo 查看我的更新答案,并查看我包含的 MSDN 链接。
    • 酷。我仍然不明白为什么它在右键单击时起作用,但至少现在我知道有不同的事件类型。再次感谢。
    【解决方案2】:

    除了 S. Akbari 的帖子,这篇文章值得一读,以了解为什么 右键单击 有效,而 左键单击 无效...

    How to use mouseDown and mouseUp on <button/>

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 2011-01-07
      • 2020-10-25
      • 2017-11-04
      • 1970-01-01
      相关资源
      最近更新 更多