如何为子菜单项创建键盘快捷键

时间:2012-03-09 08:17:30

标签: c# wpf wpf-controls

我正在使用wpf.i问题在于为菜单项创建键盘快捷键。 如何通过键盘快捷键调用子菜单项。 任何人都可以对此有所了解吗?plz帮助我...提前谢谢.. 我的.xaml文件是

    <MenuItem Header="_Open file" Name="open" IsCheckable="True"  Click="file_click"  InputGestureText="ctrl+o">

 <MenuItem.InputBindings>
   <KeyBinding Key="O" Modifiers="control"/>
                </MenuItem.InputBindings>
            </MenuItem>

我的.cs文件中的clickevent是

   private void file_click(object sender, RoutedEventArgs e)
       {



        OpenFileDialog ofd;
        ofd = new OpenFileDialog();
        ofd.AddExtension = true;
        ofd.DefaultExt = "*.*";
        ofd.Filter = "media (*.*)|*.*";
        ofd.ShowDialog();
        mediaElement1.Source = new Uri(ofd.FileName);
        listBox1.Items.Add(ofd.SafeFileName);
        mediaElement1.Play();



    }

1 个答案:

答案 0 :(得分:0)

在你的XAML中试试这个:

<Window.CommandBindings>
    <CommandBinding Command="Open" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
<Window.InputBindings>
    <KeyBinding Command="Open" Key="O" Modifiers="control" />
</Window.InputBindings>
<Grid>
    <MenuItem Header="_Open file" Name="open" IsCheckable="True" Command="Open"  InputGestureText="ctrl+o" DockPanel.Dock="Top">            
    </MenuItem>        
</Grid>

代码背后:

 private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {
        OpenFileDialog ofd;
        ofd = new OpenFileDialog();
        ofd.AddExtension = true;
        ofd.DefaultExt = "*.*";
        ofd.Filter = "media (*.*)|*.*";
        ofd.ShowDialog();
    }