I am learning about MVVM and Commands in WPF. I have a couple of buttons and I want to trigger similar commands depending on the fact if the buttons are clicked with the left or right mouse button.
Until now I used Event Handlers and I was able to determine which mouse button was pressed by checking the MouseButtonEventArgs.
<Button Content="Command Test" PreviewMouseDown="Button_PreviewMouseDown"/>
Current code behind:
private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
if (e.LeftButton == MouseButtonState.Pressed) {
Debug.Print("Left");
}
else {
Debug.Print("Right");
}
}
But I don’t see anything similar if I use Commands.
How can I set different commands for a button? One command when the left mouse button is clicked and another command when the right mouse button is clicked?
<Button Content="Command Test" Command="{Binding PressLetterCommand, Mode=OneWay}"/>
Currently the Command only fires when the left mouse button is clicked. If the command would also be fired if the right mouse button is clicked and I can find out which button was clicked that would be also a solution.
I searched and I found this question and answer which uses Decorator. How do I bind a command to e.g. the right mouse button in a ControlTemplate in WPF? I tried it but as far as I understand this won’t work for my buttons.
Any suggestions?
Try this
<Button Content="Command Test">
<Button.InputBindings>
<MouseBinding Gesture="RightClick" Command="{Binding PressLetterCommand}" />
</Button.InputBindings>
</Button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With