Jakob Busk Sørensen
Jakob Busk Sørensen

Reputation: 6081

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!");
}

Upvotes: 1

Views: 2412

Answers (2)

Jakob Busk S&#248;rensen
Jakob Busk S&#248;rensen

Reputation: 6081

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

Upvotes: 1

Salah Akbari
Salah Akbari

Reputation: 39956

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, i.e it will go down of the VisualTree hierarchy, and so the Tunnel events are triggered before the Bubble events.

Upvotes: 3

Related Questions