简体   繁体   中英

WPF Button Command for right mouse button?

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

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