简体   繁体   中英

MouseUp event doesnt work on left click

I am making a GUI using Windows Presentation Foundation (WPF). When I mouse click a button (left or right), I want a message box shown. So far I have managed to make an example from tutorials, but it only works when I right-click , and not when I left-click the button. I cannot see anything in my code, which should prevent left-click from working, so I hope you can help me.

XAML code

<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# code

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

You can subscribe to the PreviewMouseUp 's Tunneled event instead of MouseUp :

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

The PreviewMouseUp 's Routing strategy is Tunneling , ie it will go down of the VisualTree hierarchy, and so the Tunnel events are triggered before the Bubble events .

In addition to S. Akbari's post, this one is worth reading in order to understand why right-click works, and left-click does not...

How to use mouseDown and mouseUp on <button/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM