1

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that did the trick. Any chance you can also explain why? :-)
@Noceo See my updated answer and also have a look at the MSDN links that I included.
Cool. I still don't get why it worked on right click though, but at least now I know that there are different event types. Thanks once again.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.