2010-06-15 63 views
1

即時通訊新的WPF,所以我可能會失去一些東西。我在我的MainWindow類中有一個名爲StartService的簡單函數。我想用快捷鍵Ctrl + S將菜單項「Start Service」添加到我的應用程序中。我必須做到以下幾點:WPF菜單快捷鍵和自定義路由命令

  1. 在我的主窗口類,我不得不定義:

    public static RoutedCommand StartServiceRoutedCmd = new RoutedCommand();

  2. 在我的XAML代碼我補充說:

<MenuItem Header="_Start Service" InputGestureText="Ctrl+S" Click="OnStartService" /> 

<Window.CommandBindings> 
    <CommandBinding Command="{x:Static loc:MainWindow.StartServiceRoutedCmd}" 
        Executed="OnStartService" /> 
</Window.CommandBindings> 

<Window.InputBindings> 
    <KeyBinding Command="loc:MainWindow.StartServiceRoutedCmd" Gesture="CTRL+S" /> 
</Window.InputBindings> 

事情正在工作。我想知道這是否是正確和有組織的方式?我將需要我的StopService函數的快捷方式。這是否意味着我需要爲每個我需要的快捷方式定義一個新的RoutedCommand StopServiceRoutedCmd,等等。

+0

是的,您需要一個新的RoutedCommand來停止服務。其他一切都很好。 – Amsakanna 2010-06-15 10:22:00

+0

我實際上意識到我的菜單項應該也是這樣的: 這樣,我添加了一個CanStartService()。 我很高興知道我在正確的軌道上。 :) – Tamer 2010-06-15 10:51:24

+0

我認爲你在使用基於事件的方法之前,同時轉化爲忘記改變命令:)是的!你需要在那裏使用一個命令。有時候,您可能無法從事件轉換爲命令。爲此,您可以使用MVVM Light Toolkit的EventToCommand行爲,這將更加有用。 http://www.galasoft.ch/mvvm/getstarted/ – Amsakanna 2010-06-15 11:56:04

回答

2
<MenuItem Header="_Start Service" InputGestureText="Ctrl+S" Command="loc:MainWindow.StartServiceRoutedCmd /> 

<Window.CommandBindings> 
     <CommandBinding Command="{x:Static loc:MainWindow.StartServiceRoutedCmd}" 
       Executed="OnStartService" /> 
     </Window.CommandBindings> 

<Window.InputBindings> 
     <KeyBinding Command="loc:MainWindow.StartServiceRoutedCmd" Gesture="CTRL+S" /> 
</Window.InputBindings>