2010-11-15 166 views
10

我有遵循MVVM模式的WPF應用程序。我需要實現鍵盤快捷鍵。這些快捷方式必須控制WebBrowser控件行爲。我定義了第一個自定義命令並添加到了視圖的輸入綁定中。將有更多的命令,他們將不得不在瀏覽器中調用腳本:WPF MVVM中的鍵盤快捷鍵?

MainWindow.xaml.cs:

 ... 

     CommandBinding cb = new CommandBinding(RemoteControlCommands.TestCommand, MyCommandExecuted, MyCommandCanExecute); 
     this.CommandBindings.Add(cb); 

     KeyGesture kg = new KeyGesture(Key.Q, ModifierKeys.Control); 
     InputBinding ib = new InputBinding(RemoteControlCommands.TestCommand, kg); 
     this.InputBindings.Add(ib); 
    } 

    private void MyCommandExecuted(object sender, ExecutedRoutedEventArgs e) 
    { 
     webBrowser.InvokeScript("foo", "Hello World!"); 
    } 

    private void MyCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) 
    { 
     e.CanExecute = true; 
    } 

我的問題是如何適應MVVM百通呢? MVVM對我來說是一個新概念,但我理解如何將視圖的命令綁定到視圖模型,並執行方法或更改屬性。 但是在這種情況下,我需要在視圖中的控件上執行一個方法。在這種情況下快捷處理的最佳位置是什麼?

回答

38
<Window.InputBindings> 
    <KeyBinding Command="{Binding MyCommand, Source=viewModel...}" 
       CommandParameter="{Binding,ElementName=browserControl,Mode=Self}" 
       Gesture="CTRL+R" /> 
</Window.InputBindings> 

您可以將命令屬性綁定到View Model的命令。

+0

然後呢?查看模型不知道關於瀏覽器控件鑑於我想要調用 – jlp 2010-11-15 17:03:36

+0

上的方法您可以將命令參數綁定到某個值,如webbrowser本身,並在您的委託方法中檢索它。 – 2010-11-16 04:51:23

+1

+1,非常好的語言結構,沒有遇到過 – 2010-11-16 08:33:36