2015-07-20 26 views
1

我需要在WPF應用程序中編寫一個keylistener。我希望能夠處理任何鍵。該應用程序符合MVVM模式。如何編寫一個方便的MVVM-Keylistener

我知道純XAML的解決方案,但它不是萬能的每一個關鍵:

<KeyBinding Key="Enter" Command="{Binding SearchCommand}" CommandParameter="EnterPressed" /> 

我不想寫這篇文章的每一個可能的密鑰。有什麼辦法可以實現不會中斷MVVM的方便的KeyListener嗎?

回答

0

我發現了一個簡單的方法來將按下的鍵綁定到ViewModel中的一個變量,而不會中斷MVVM模式。它採用了綁定,創建和填寫代碼隱藏:

  1. 創建的DependencyProperty,並在窗口的構造函數綁定:

    Binding binding = new Binding(); 
    binding.Path = new PropertyPath("pressedKey"); 
    binding.Source = DataContext; 
    binding.Mode = BindingMode.OneWayToSource; 
    dp = DependencyProperty.Register("pressedKey", typeof(string), typeof(MainWindow)); 
    BindingOperations.SetBinding(this, dp, binding); 
    
  2. 在XAML中設置一個事件處理程序:

    KeyDown="KeyDown_Handler" 
    
  3. 指定按鍵的DependencyProperty的值:

    private void KeyDown_Handler(object sender, KeyEventArgs e) 
    { 
        SetValue(dp, e.Key.ToString()); 
    } 
    

如果公衆pressedKey -Variable在ViewModel中存在,它將包含按下的按鍵。在設置塊或通過調用ViewModel執行命令(((ICommand)DataContext).Execute(...)),您可以立即處理按下的鍵

相關問題