2010-06-15 64 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>