WPF 中Menu自定义快捷键

来源:互联网 发布:java中如何用api接口 编辑:程序博客网 时间:2024/05/28 05:16

前几天适用Menu控件,在使用自定义快捷键的时候遇到问题,现已解决,代码如下:

前台:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="local:DataCommands.Requery" Executed="MenuItem_Click" />
    </Window.CommandBindings>
    <Grid>
        <Menu>
            <MenuItem Header="Tools">
                <MenuItem Header="_快捷键"  Command="local:DataCommands.Requery" />
            </MenuItem>
        </Menu>
    </Grid>
</Window>

后台:

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Requery");
        }

    }

    public class DataCommands
   
 {
       
  private static RoutedUICommand requery;
       
  static DataCommands()
       
  {
           
   InputGestureCollection inputs = new InputGestureCollection();
           
   inputs.Add(new KeyGesture(Key.G, ModifierKeys.Control, "Ctrl+G"));
           
   requery = new RoutedUICommand(
"Requery", "Requery", typeof(DataCommands), inputs);
       
  }
        
       
  public static RoutedUICommand Requery
       
  {
 get { return requery; }
 }
   
 }
}

注意前台引用命名空间