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



我正在使用wpf。我遇到了一个问题,那就是为菜单项创建键盘快捷键。如何通过键盘快捷键调用子菜单项。有人对此有想法吗?请帮帮我..提前谢谢。。我的.xml文件是

    <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文件中的点击事件是

   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();

    }

在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();
    }

最新更新