验证失败时,将焦点保持在上一个文本框 [英] Keep Focus back to the previous Textbox on failed validation

查看:95
本文介绍了验证失败时,将焦点保持在上一个文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果验证失败,我希望焦点回到上一个文本框。我正在验证LostFocus事件上的文本框控件值。需要一些帮助。

I want Focus back to the previous Textbox if validation gets failed. I am validating the Textbox control value on lostFocus event. Need some help.

这个问题也越来越老了

在用户尝试移动到文本框后,请继续关注文本框.net 3.5 WEC7中的其他控件(验证失败),. net 3.5 WEC7

推荐答案

如果您尝试聚焦元素在它自己的 LostFocus 处理程序中,您将面临 StackOverflowException ,我不确定根本原因(我怀疑

If you attempt to focus an element inside its own LostFocus handler you will face a StackOverflowException, I'm not sure about the root cause (I suspect the focus kind of bounces around) but there is an easy workaround: dispatch it.

private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
    var element = (sender as TextBox);
    if (!theTextBoxWasValidated())
    {
        // doing this would cause a StackOverflowException
        // element.Focus();

        var restoreFocus = (System.Threading.ThreadStart)delegate { element.Focus(); };
        Dispatcher.BeginInvoke(restoreFocus);
    }
}

通过 Dispatcher.BeginInvoke ,请确保恢复焦点不会妨碍正在进行的焦点丢失(并避免您否则会遇到的讨厌异常)

Through Dispatcher.BeginInvoke you make sure that restoring the focus doesn't get in the way of the in-progress loss of focus (and avoid the nasty exception you'd face otherwise)

这篇关于验证失败时,将焦点保持在上一个文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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