阻止 WPF 文本框失去焦点 [英] Stop a WPF Textbox from losing focus

查看:53
本文介绍了阻止 WPF 文本框失去焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WPF Textbox,我想在它失去键盘/焦点之前检查文本值是否正确.

I have a WPF Textbox, that I want to check that the text value is correct before I allow it to lose keyboard/focus.

我尝试在 InputBox_LostFocus 中设置 e.Handled &InputBox_LostKeyboardFocus 事件,但它似乎没有达到我想要的效果.

I have tried setting e.Handled in the InputBox_LostFocus & InputBox_LostKeyboardFocus events, but it doesnt seem to be achieving what I want.

关于如何将焦点锁定到 Textbox 的任何建议?

Any suggestions on how I can lock focus to a Textbox?

推荐答案

您可以在 UIElement 上调用 Mouse.Capture.然后,这将为您提供无论是否在元素上发生的每个鼠标事件.但它使用起来很棘手.您可以在文本框上捕获鼠标并注册丢失的捕获事件,当您丢失捕获时可以重新捕获.你必须提防奇怪的行为.通常,不允许用户离开字段是不好的做法(我认为).更好的是允许他们为所欲为,但在输入数据后禁用他们按下的按钮,直到所有字段都有效(或类似的东西)

You can call Mouse.Capture on a UIElement. This will then give you every mouse event that hapens whether on the element or not. but its tricky to use. You can capture the mouse on your text box and register for lost capture events, when you lose capture you can recapture. you have to watch out for strange behaviors. Generally its bad practice (I think) to not allow a user to move off a field. what is better is to allow them to do whatever they want, but disable the button that they push after entering data until all fields are valid (or something similar)

这里有一些链接

其他 SO 问题

msdn 示例代码

组合框使用鼠标捕获来判断用户是否单击了应用程序中的其他位置,如果您单击另一个控件(或窗口外)打开组合框,则关闭组合框

the combo box uses mouse capture to tell if the user has clicked elsewhere in the app to close the combo box if its open if you click on another control (or outside the window)

我不知道这种技术是否会阻止您对元素进行标记.wpf 应用程序中有两种焦点.你有逻辑焦点和键盘焦点.多个元素可以同时具有逻辑焦点(每个元素都在一个焦点范围内).例如,当您单击菜单时,文本框可以具有逻辑焦点(它也具有逻辑焦点).键盘焦点一次只能在一个地方.你将为自己做很多工作.我会认真考虑您是否以正确的方式进行互动.你可以花几天时间让这种交互正确.如果你停止你的文本框失去焦点,如果用户点击关闭按钮会发生什么?

I dont know if this technique will stop you tabbing off the element. there are two kinds of focus in a wpf app. You have logical focus and keyboard focus. Multiple elements can have logical focus at once (each within a focus scope). think for example a textbox can have logical focus while you are clicking a menu (which has logical focus as well). Keyboard focus can only be in one place at a time. You are going to make a lot of work for yourself. I would seriously consider if you are doing your interaction in the right way. You could spend days getting this interaction correct. If you stop your textbox losing focus, what happens if the user clicks the close button?

这里是 msdn 重点文章

这篇关于阻止 WPF 文本框失去焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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