Keep Focus back to the previous Textbox on failed validation

半城伤御伤魂 提交于 2019-12-13 04:39:29

问题


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.

This question was eralier too link is

Keep Focus on Textbox after user tried to move to other control (on failed validation) in winforms, .net 3.5 WEC7


回答1:


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);
    }
}

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)



来源:https://stackoverflow.com/questions/22403979/keep-focus-back-to-the-previous-textbox-on-failed-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!