当有验证错误时,防止丢失TextBox焦点的最佳方法是什么? [英] What's the best way to prevent losing TextBox focus when there is a validation error?

查看:164
本文介绍了当有验证错误时,防止丢失TextBox焦点的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我弄乱了 PreviewLostKeyboardFocus 这几乎让你在那里。我已经看到了一些使用 LostFocus 的实现,但是它只是在焦点丢失之后强制回到 TextBox 你可以很容易地看到这个在屏幕上移动。基本上,我只是寻找在WinForms中使用 OnValidating 的相同类型的行为。

解决方案

在我看来,最好的办法一般不是这样做的。但是如果你的设计真的需要这个能力的话,那么你应该做的是什么:


  1. 截取您的键盘和鼠标事件的预览版本窗口级别,或任何范围,你想防止焦点内的变化(例如可能不是你的菜单栏)。

  2. 当检测到Tab键或返回KeyDown文本框中,或者当它有焦点时在文本框外部检测到MouseDown时,请在绑定表达式上调用UpdateSource(),如果验证失败,则设置Handled = true以防止KeyDown或MouseDown事件被进一步处理。继续处理 PreviewLostKeyboardFocus 来捕捉任何不是来自键盘的焦点变化的原因。

  3. 或鼠标,或者您的其他代码无法识别。


I've messed around with PreviewLostKeyboardFocus which almost gets you there. I've seen a couple of implementations using LostFocus, but that just forces focus back on the TextBox after it's lost focus and you can easily see this shifting on the screen. Basically, I'm just looking for the same type of behavior you could get with using OnValidating in WinForms.

解决方案

In my opinion, the best way is generally not to do it. It is almost always better to just disable the other controls or prevent saving until the value is valid.

But if your design really needs this ability, here is what you should do:

  1. Intercept the Preview version of keyboard and mouse events at your window level, or whatever scope you want to prevent focus changes within (eg maybe not your menu bar).

  2. When the Tab KeyDown or Return KeyDown is detected in the text box, or when a MouseDown is detected outside the text box while it has the focus, call UpdateSource() on the binding expression, then if the validation has failed set Handled=true to prevent the KeyDown or MouseDown event from being processed further.

  3. Also continue handling PreviewLostKeyboardFocus to catch any causes of focus change that aren't from the keyboard or mouse, or that your other code didn't recognize.

这篇关于当有验证错误时,防止丢失TextBox焦点的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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