WPF 热键触发无需修饰符
我有一个 WPF 窗口,其中包含一个名为“取消”的按钮。一般情况下,我希望用户能够按 Alt+C 取消操作并关闭程序。因此,该按钮的标题为“_Cancel”。
问题 1:在 Window_Load 期间,如果我按 C(不带修饰符),则会触发 Cancel_Clicked 事件,并且程序关闭。
问题 2:在我的程序打开后,假设我不与窗口上的任何内容进行交互,则按不带修饰符的 C 将关闭程序。
请注意,由于问题 2,使用某种布尔值来跟踪“已加载”状态将不起作用。
我做错了什么?有什么想法吗?
I have a WPF window, which contains a button called Cancel. Under ordinary circumstances I want a user to be able to press Alt+C to cancel their actions and close the program. As such, the button is captioned "_Cancel."
Problem 1: During Window_Load, if I press C without modifiers, the Cancel_Clicked event fires, and the program closes.
Problem 2: After my program opens, assuming I don't interact with anything on the window, pressing C without modifiers will close the program.
Note that, due to problem 2, using some sort of boolean to track the "loaded" status won't work.
What am I doing wrong? Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最好的解决方案是将其重构为 命令:< /a>
Your best solution is to refactor this into a command:
看起来这是标准行为。 (嘘!)
WPF 加速键,如 Visual Studio
http://blogs.msdn.com/saraford/archive/2004/04/16/ 114935.aspx
It looks like this is standard behavior. (Boo!)
WPF Accelerator Keys like Visual Studio
http://blogs.msdn.com/saraford/archive/2004/04/16/114935.aspx
我发现这与 WinForms 中的行为相同。 (我也不敢相信,直到我创建了一个测试项目来尝试它!)。这是之前针对相同场景的 SO 问题: WPF Accelerator Keys like Visual Studio< /a>
如果您想强制热键始终由 Alt 修饰符触发,您可以考虑将操作重构为命令。
这是一个非常快速且简单的演示,说明如何实现这样的命令。
I've found that this is the same behavior that is in WinForms. (I was in disbelief as well until I created a test project to try it out!). Here is a previous SO question that hits on the same scenario: WPF Accelerator Keys like Visual Studio
If you want to force the hotkey to ALWAYS be triggered with an Alt modifier, you could consider refactoring the action into a command.
Here is a very quick and hacky demonstration on how one might go about implementing such a command.