WPF 在没有焦点的情况下接受输入
我在 WPF 中创建了一个屏幕,它接受来自条形码扫描仪的输入。我监听 PreviewTextInput 事件和 KeyUp 事件,这让我可以确定扫描仪“输入”的内容以及完成的时间。效果很好。您只需显示表格,它就会接受条形码扫描。
问题是,我的页面上还有其他控件,它们导致了问题。例如,当您按下表单上的按钮时,该按钮就会获得焦点。从该点开始按 Enter 键会导致触发按钮事件处理程序。它不会自动放弃焦点。
有谁知道此类问题的优雅解决方案?我不想向每个事件处理程序添加代码来聚焦另一个元素,但我将这样做作为最后的手段。
I've created a screen in WPF that accepts input from a barcode scanner. I listen to PreviewTextInput event, and the KeyUp event, which let's me determine what the scanner "typed", and when it finished. It works great. You just have to have the form displayed and it will accept barcode scans.
The problem is, I have other controls on the page, and they're causing issues. For example, when you push a button on the form, that button then has focus. Hitting the enter key from that point on results in the button event handler being fired. It doesn't automatically give up focus.
Does anyone know an elegant solution to this type of problem? I'd rather not add code to every event handler to focus another element, but I will do that as a last resort.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Button
(实际上是UIElement
)有一个用于此特定目的的属性:UIElement.Focusable。如果您在 xaml 或代码中将其设置为 false,您仍然可以单击该按钮,但它不会将焦点从其他 UIElement 上移开。
Button
(actuallyUIElement
) has a property for this specific purpose: UIElement.Focusable.If you set this to false in your xaml or code, you can still click on the button, but it will not take focus away from other UIElements.
我们只需设置按钮属性即可启用这些功能。
接受按钮 -
Button.IsDefault = "True"
取消按钮 -
Button.IsCancel = "True"
We just have to set the button attributes for enable those features.
Accept Button -
Button.IsDefault = "True"
Cancel Button -
Button.IsCancel = "True"
PreviewTextInput
事件可以更改焦点(如果按钮有焦点,则散焦),以便当按下条形码末尾的 Enter 键时,按钮不会被按下。The
PreviewTextInput
event could change the focus (defocus if a button has it) so that when the enter key at the end of a barcode hits, the button wouldn't get pressed.