WPF Menu实现快捷键操作

很多小伙伴说,在Menu中,实现单个快捷键操作很简单,怎么实现多个快捷键操作和,组合快捷键呢,今天他来了。

上代码和效果图

一、Ctrl + Shift + 任意子母键实现快捷键组合

<Window x:Class="XH.TemplateLesson.MenuWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:XH.TemplateLesson"
        mc:Ignorable="d"
        Title="MenuWindow" Height="450" Width="800">
 <Window.InputBindings>
   <!-- 定义组合快捷键 Ctrl+Shift+S -->
   <!--先要什么组合修改key 或者 Modifiers 即可
     注意:这里只可以改为Ctrl Alt Shift Windows + 任意字母键的快捷方式-->
   <KeyBinding Key="S" Modifiers="Control+Shift" Command="{Binding NewCommand}" />
 </Window.InputBindings>
 <Grid>
   <Menu>
    <MenuItem Header="新建(_F)">
        <MenuItem Header="新建" />
        <MenuItem Header="全部保存" Command="{Binding NewCommand}" InputGestureText="Ctrl+Shift+S"  />
    </MenuItem>
    <MenuItem Header="编辑(_E)"/>
  </Menu>
  </Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace XH.TemplateLesson
{
    /// <summary>
    /// MenuWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MenuWindow : Window
    {
        public ICommand NewCommand { get; set; }
        public MenuWindow()
        {
            InitializeComponent();
            DataContext = this;
            NewCommand = new RelayCommand(ExecuteNew);
        }
        private void ExecuteNew(object parameter)
        {
            MessageBox.Show("New Command Executed");
        }


        public class RelayCommand : ICommand
        {
            private readonly Action<object> _execute;
            private readonly Func<object, bool> _canExecute;

            public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
            {
                _execute = execute;
                _canExecute = canExecute;
            }

            public bool CanExecute(object parameter)
            {
                return _canExecute == null || _canExecute(parameter);
            }

            public void Execute(object parameter)
            {
                _execute(parameter);
            }

            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
        }
    }
}

直接Ctrl + Shift + S弹出:

二、实现Ctrl + 多个字母键组合

<Window x:Class="XH.TemplateLesson.MenuWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:XH.TemplateLesson"
        mc:Ignorable="d" 
        <!--绑定键盘事件-->
        PreviewKeyDown="Window_PreviewKeyDown"
        PreviewKeyUp="Window_PreviewKeyUp"
        Title="MenuWindow" Height="450" Width="800">
  <Grid>
    <Menu>
      <MenuItem Header="新建(_F)">
          <MenuItem Header="新建" />
          <MenuItem Header="整理代码格式" InputGestureText="Ctrl+K+D"  />
      </MenuItem>
    </Menu>
  </Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace XH.TemplateLesson
{
    /// <summary>
    /// MenuWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MenuWindow : Window
    {
        private bool _isCtrlPressed;
        private bool _isAPressed;
        public MenuWindow()
        {
            InitializeComponent();
        }
        // 下方的K 和D 根据自己写的代码来进行修改
        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            // 先 Cttrl
            if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
            {
                _isCtrlPressed = true;
            }
            // 再 Ctrl + K 
            else if (e.Key == Key.K && _isCtrlPressed)
            {
                _isAPressed = true;
            }
            // 最后 Cttrl + K + D
            else if (e.Key == Key.D && _isCtrlPressed && _isAPressed)
            {
                ExecuteCustomCommand();
            }
        }
        // 键盘释放 如果释放 无效
        private void Window_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
            {
                _isCtrlPressed = false;
            }
            else if (e.Key == Key.K)
            {
                _isAPressed = false;
            }
        }

        private void ExecuteCustomCommand()
        {
            MessageBox.Show("快捷键调用成功: Ctrl + K + D");
        }
    }
}

按下Ctrl + K + D:

单键 Alt + 字母弹出

<Menu>
  <!--直接下划线 + 字母 就可以alt + 字母弹出-->
  <MenuItem Header="新建(_F)">
    <MenuItem Header="新建" />
    <MenuItem Header="整理代码格式" InputGestureText="Ctrl+K+D"  />
  </MenuItem>
</Menu>

演示 :

好了,以上就是WPF中Menu控件中,所有快捷键的使用方法了,感觉有用的话,点个赞呗。

<think>我们正在讨论WPF多级菜单的实现。用户需要实现多级菜单,通常指的是嵌套的菜单结构,例如主菜单项下包含子菜单,子菜单可能还有更深层级的子菜单。在WPF中,可以使用Menu控件和MenuItem控件来实现多级菜单。MenuItem控件可以包含其他的MenuItem控件,从而形成嵌套结构。实现步骤:1.在XAML中,使用Menu作为容器,每个顶级菜单项是一个MenuItem。2.在MenuItem中,可以设置Header属性作为显示的文本。3.为了实现多级菜单,可以在MenuItem中嵌套MenuItem,作为子菜单项。示例代码:下面是一个简单的多级菜单示例,包含“文件”菜单,其下有“新建”和“退出”两个子菜单,而“新建”菜单下又有“项目”和“文件”两个子菜单。 ```xml<Windowx:Class="WpfApp.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="MainWindow"Height="350"Width="500"><Grid><Menu><MenuItem Header="文件"><MenuItemHeader="新建"><MenuItem Header="项目"/><MenuItemHeader="文件"/></MenuItem><Separator/> <!--分隔线 --><MenuItem Header="退出"/></MenuItem><MenuItemHeader="编辑"/><MenuItem Header="帮助"/></Menu></Grid> </Window>```在这个例子中,“文件”菜单项包含了一个子菜单项“新建”,而“新建”又包含了两个子菜单项“项目”和“文件”。这样我们就实现了一个两级菜单。如果需要更多层级,继续嵌套MenuItem即可。另外,我们还可以为菜单项添加事件处理(例如Click事件)来执行相应的命令。如果需要动态生成菜单,可以在代码中动态创建MenuItem对象并添加到菜单中。动态生成菜单示例(C#代码): ```csharp//假设我们有一个Menu控件,名为mainMenuMenu mainMenu =new Menu();MenuItem fileMenuItem= newMenuItem{ Header= "文件"}; mainMenu.Items.Add(fileMenuItem);MenuItemnewMenuItem= newMenuItem{ Header= "新建"}; fileMenuItem.Items.Add(newMenuItem);MenuItem projectMenuItem =new MenuItem {Header ="项目" };newMenuItem.Items.Add(projectMenuItem); projectMenuItem.Click+= (sender, e) =>{ /*处理新建项目的逻辑*/ };// ...类似地添加其他菜单项```这样,我们就可以在运行时动态构建菜单。注意事项: -菜单项可以使用Separator来添加分隔线。-菜单项可以设置图标(通过Icon属性)、快捷键(通过InputGestureText属性)等。-菜单项可以绑定命令(Command属性)来实现MVVM模式。在MVVM模式中,我们可以将菜单项绑定到ViewModel中的命令,这样可以使界面与逻辑分离。例如,使用MVVM模式绑定命令:在ViewModel中定义一个命令:```csharppublic ICommand NewProjectCommand{ get; privateset;} publicMainWindowViewModel(){NewProjectCommand =new RelayCommand(ExecuteNewProject);} privatevoid ExecuteNewProject() {//执行新建项目的逻辑} ```在XAML中绑定:```xml<MenuItem Header="项目" Command="{BindingNewProjectCommand}"/> ```这样,当点击“项目”菜单项时,就会执行NewProjectCommand绑定的命令。总结:WPF实现多级菜单主要依靠MenuMenuItem控件的嵌套使用,可以通过XAML静态定义,也可以通过代码动态生成,同时支持MVVM模式绑定命令。 §§相关问题§§1. WPF中如何为菜单项添加快捷键? 2.如何在WPF实现右键上下文菜单(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值