Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Button Command for right mouse button?

Tags:

c#

command

mvvm

wpf

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?

like image 704
Edgar Avatar asked Oct 16 '15 08:10

Edgar


Video Answer


1 Answers

Try this

<Button Content="Command Test">
    <Button.InputBindings>
        <MouseBinding Gesture="RightClick" Command="{Binding PressLetterCommand}" />
    </Button.InputBindings>
</Button>
like image 102
Lonli-Lokli Avatar answered Oct 16 '22 19:10

Lonli-Lokli