简体   繁体   English

键绑定到 c# wpf 中的按钮元素

[英]Key Binding to a button element in c# wpf

I have a print button in my application which prints the receipt.我的应用程序中有一个打印按钮,用于打印收据。 However user prefers having a shortcut key (no combination with shift or Alt, instead it should be just a single key press say F2).但是,用户更喜欢使用快捷键(不与 shift 或 Alt 组合,而应该只是一个按键,比如 F2)。 On press of this button, I should call the printReceipt() method which I was calling on click of print button.按下此按钮时,我应该调用 printReceipt() 方法,我在单击打印按钮时调用该方法。

I am trying to add a keybinding to the user control as the button element is in user control like below我正在尝试向用户控件添加键绑定,因为按钮元素位于用户控件中,如下所示

<UserControl.InputBindings>
<KeyBinding Key="F1" Command="{Binding PrintReceipt}" />
</UserControl.InputBindings>

I am a beginner and can anyone suggest me what is the best way to handle such use case?我是初学者,谁能建议我处理这种用例的最佳方法是什么?

You can subscribe to PreviewKeyDown of the form.您可以订阅 PreviewKeyDown 表单。 There you can obtain the model from DataContext property and call PrintReciept.在那里,您可以从 DataContext 属性中获取 model 并调用 PrintReciept。

This does not violate MVVM principles and is easy to understand.这不违反 MVVM 原则,并且易于理解。 Also, not much magic happening imho.此外,恕我直言,并没有发生太多的魔法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM