在Wpf应用程序中实现快捷键

3

我刚接触WPF应用程序,现在正在开发一个菜单。我已经创建了菜单,但是我想要将菜单项的事件与快捷键进行绑定,如ctrl+o、ctrl+n等。请告诉我具体如何做。


http://blogs.windowsclient.net/vsdev/archive/2009/03/30/wpf-menu-how-to-implement-shortcut-keys.aspx - Kendrick
@Anu 你正在使用哪个框架进行开发... .Net 4.0 还是 .Net 3.5 ?? - Ankesh
我正在使用VS2010,即4.0版本。 - Anu
2个回答

3

您可以按以下方式完成...

在Xaml文件中

<Window x:Class="FocusDemo.Window1"  
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    xmlns:local="clr-namespace:FocusDemo"  
Title="Window1" Height="300" Width="300">  

<Window.CommandBindings>  
    <CommandBinding   
        Command=   
        "{x:Static   
        local:Window1.CustomRoutedCommand}"                       
        Executed="ExecutedCustomCommand"   
        CanExecute="CanExecuteCustomCommand" >  
    </CommandBinding>  
</Window.CommandBindings>  
<Window.InputBindings>  
    <KeyBinding   
        Command=  
        "{x:Static   
        local:Window1.CustomRoutedCommand}"   
        Key="S"   
        Modifiers="Control"/>  
</Window.InputBindings>
<Grid>
<!--Your Controls-->
</Grid>
</Window>  

在代码后台文件中

    /// <summary>  
/// Interaction logic for Window1.xaml  
/// </summary>  
public partial class Window1 : Window  
{  
    public static RoutedCommand CustomRoutedCommand = new RoutedCommand();    
    public Window1()  
    {             
        InitializeComponent();       
    }  
    #region  
    public void ExecutedCustomCommand(object sender, ExecutedRoutedEventArgs e)  
    {  
        MessageBox.Show("Ctrl+S");  
    }  


    public void CanExecuteCustomCommand(object sender,  
        CanExecuteRoutedEventArgs e)  
    {  
        e.CanExecute = true;  
    }  
    #endregion   
    
}  

来源: 点击这里

如果答案正确请不要忘记标记


0

我知道这不是问题的确切答案,但可能像我一样的人正在寻找将任何键盘快捷方式放置到菜单项(命令按钮)中的方法,例如Alt+O、Alt+N。在这种情况下,您只需在项目名称中的快捷字符前面放置下划线字符(_)即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接