2015-10-16 86 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