2015-10-16 85 views
2

我正在学习WPF中的MVVM和命令。我有几个按钮,并且我想根据事实触发类似的命令,如果用鼠标左键或右键单击按钮。用于鼠标右键的WPF按钮命令?

到现在为止我使用了事件处理程序,并且通过检查MouseButtonEventArgs,我能够确定按下了哪个鼠标按钮。

<Button Content="Command Test" PreviewMouseDown="Button_PreviewMouseDown"/> 

当前的代码背后:

private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e) 
    if (e.LeftButton == MouseButtonState.Pressed) { 
     Debug.Print("Left"); 
    } 
    else { 
     Debug.Print("Right"); 
    } 
} 

但我不明白,如果我使用命令类似的事情。

如何为按钮设置不同的命令?单击鼠标左键时的一个命令,单击鼠标右键时的另一个命令?

<Button Content="Command Test" Command="{Binding PressLetterCommand, Mode=OneWay}"/> 

当前命令仅在点击鼠标左键时触发。如果点击鼠标右键也会触发该命令,我可以找出哪个按钮被点击,这也是一个解决方案。

我搜索,我发现这个问题和答案,它使用装饰。 How do I bind a command to e.g. the right mouse button in a ControlTemplate in WPF?我试过了,但据我了解,这不适用于我的按钮。

有什么建议吗?

+1

单击一个按钮时,如果不管它是鼠标左右键,或键盘,如果它具有焦点。这就是为什么它有一个Click事件和一个Command。不要改变这种行为。 – Clemens

+0

更改按钮的标准行为有什么好处?你看到了多少个应用程序,这些应用程序在右键单击按钮时有一些行为? – Dennis

+0

@Clemens:我使用从A到Z的字母按钮让用户在通常只用鼠标使用的窗体上输入一些小文本。如果点击鼠标左键,那么字母是大写字母,右键是小写字母。这可能并不完美,但我喜欢它不仅仅是一个额外的Shift按钮,还有另外26个用于小写字符的按钮。 – Edgar

回答

12

试试这个

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

'Command'属性应该使用绑定。 – Dennis

+0

谢谢你的工作正常。我花了一个小时尝试这个,然后在10分钟内得到一个关于StackOverflow的答案。精彩! – Edgar