在WPF中使用快捷方式创建菜单的正确方法 [英] Correct way to create a menu with shortcuts in WPF

查看:99
本文介绍了在WPF中使用快捷方式创建菜单的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用热键快捷方式创建菜单的正确/最佳方法是什么?

What is the correct/best way to create a menu with hotkey shortcuts?

我只是想要像Visual Studio一样的File菜单,该菜单具有New,Open,Save,Save All,Exit和其他一些标准快捷键.

I simply want a File menu like Visual Studio's that has New, Open, Save, Save All, Exit, and a few other standard shortcuts.

似乎InputGestureText显示了适当的文本,但是由于它被称为文本"并且似乎不会触发事件,因此我将假定这不是正确的方法. Command体系结构似乎也相当庞大,因此,如果有更好的方法,我不想走这条路.

It seems that InputGestureText displays the appropriate text, but since it's called "Text" and doesn't seem to trigger events, I'm going to assume that isn't the right way to do it. The Command architecture also seems fairly bulky, so I don't want to head down that path if there is a better way.

更新: 为了清楚起见,假设我使用以下菜单:

Update: For clarity, let's say I'm using the following menu:

<Menu>
  <MenuItem Header="_File">
    <MenuItem Header="_New" />
    <MenuItem Header="_Open" />
    <Separator />
    <MenuItem Header="_Save" />
    <MenuItem Header="Save _All" />
    <Separator />
    <MenuItem Header="_Export"/>
    <MenuItem Header="_Import"/>
    <Separator />
    <MenuItem Header="E_xit"/>
  </MenuItem>
</Menu>

其中导出"和导入"将是自定义快捷方式;微软没有将其构建为诸如ApplicationCommands之类的东西.您能否提供完整的解决方案,必要时包括C#自定义代码? (它不仅可以帮助我,而且希望可以帮助其他正在寻找类似问题的人.)

where Export and Import would be custom shortcuts; something that Microsoft didn't build into something like ApplicationCommands. Can you please provide a complete solution, including C# custom code if necessary? (Not only will it help me out, but I hope to help anyone else out who is searching for similar issues.)

推荐答案

您正确地注意到InputGestureText实际上并未设置快捷方式,它只是在菜单上标记了快捷方式.正确的方法是使用窗口的InputBindings.您可以将键盘快捷键映射到任何命令,包括您自己的模型定义的命令.但是,为了使它起作用,您需要使用绑定到命令的菜单项-而不是直接处理其单击事件.这是在WPF中处理菜单命令的推荐方法.否则,您将需要使用老式的键盘事件处理.

You are correct in noting that InputGestureText does not actually set up a shortcut, it simply labels it on the menu. The correct way to do it is to use the InputBindings of the window. You can map a keyboard shortcut to any command, including your own model-defined commands. But in order for this to work, you need to use menu items bound to commands - not handle their click events directly. This is the recommended way of handling menu commands in WPF. Otherwise you'll need to resort to old fashioned keyboard event handling.

<Window.InputBindings>
  <KeyBinding Key="A" Modifiers="Control" Command="{Binding MyAwesomeCommand}" />
</Window.InputBindings>

有关MSDN的更多信息.

这篇关于在WPF中使用快捷方式创建菜单的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆