wpf 鼠标右键的WPF按钮命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33166055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:28:48  来源:igfitidea点击:

WPF Button Command for right mouse button?

c#wpfmvvmcommand

提问by Edgar

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.

我正在学习 WPF 中的 MVVM 和命令。我有几个按钮,我想根据是用鼠标左键还是鼠标右键单击这些按钮来触发类似的命令。

Until now I used Event Handlers and I was able to determine which mouse button was pressed by checking the MouseButtonEventArgs.

到目前为止,我使用了事件处理程序,并且能够通过检查 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.

我搜索并找到了这个使用装饰器的问题和答案。如何将命令绑定到例如 WPF 中 ControlTemplate 中的鼠标右键?我试过了,但据我所知,这对我的按钮不起作用。

Any suggestions?

有什么建议?

回答by Lonli-Lokli

Try this

尝试这个

<Button Content="Command Test">
    <Button.InputBindings>
        <MouseBinding Gesture="RightClick" Command="{Binding PressLetterCommand}" />
    </Button.InputBindings>
</Button>