C# 带有快捷方式和自定义RoutedCommand的WPF菜单

C# 带有快捷方式和自定义RoutedCommand的WPF菜单,c#,wpf,shortcuts,routedcommand,C#,Wpf,Shortcuts,Routedcommand,我是WPF的新手,所以我可能错过了一些东西。在我的主窗口类中有一个简单的函数叫做StartService。我想在我的应用程序中添加一个带有快捷键Ctrl+S的菜单项“启动服务”。我必须做到以下几点: 在我的MainWindow类中,我必须定义: public static RoutedCommand StartServiceRoutedCmd=new RoutedCommand() 在我的XAML代码中,我添加了: 事情进展顺利。我想知道这是不是正确且有条理的方法?我需要一个快捷方式来实现

我是WPF的新手,所以我可能错过了一些东西。在我的主窗口类中有一个简单的函数叫做StartService。我想在我的应用程序中添加一个带有快捷键Ctrl+S的菜单项“启动服务”。我必须做到以下几点:

  • 在我的MainWindow类中,我必须定义:

    public static RoutedCommand StartServiceRoutedCmd=new RoutedCommand()

  • 在我的XAML代码中,我添加了:

  • 
    

    事情进展顺利。我想知道这是不是正确且有条理的方法?我需要一个快捷方式来实现我的停止服务功能。这是否意味着我需要为我需要的每个快捷方式定义一个新的RoutedCommand StopServiceRoutedCmd,依此类推?

    是的,您需要一个新的RoutedCommand来停止服务。其他一切看起来都很好。我实际上意识到我的菜单项条目也应该是这样的:这样,如果我添加了一个CanStartService(),我到处都会得到验证。我很高兴知道我走上了正确的道路。:)我认为您在使用基于事件的方法之前和转换为命令时忘记了更改:)是的!您需要在那里使用命令。有时,从事件更改为命令时可能会遇到问题。为此,您可以使用MVVM Light Toolkit的EventToCommand行为,这将更加有用。
    
    <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>
    
    <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>