What's the best way to prevent losing TextBox focus when there is a validation error?

前端 未结 3 406
不思量自难忘°
不思量自难忘° 2021-02-04 20:44

I\'ve messed around with PreviewLostKeyboardFocus which almost gets you there. I\'ve seen a couple of implementations using LostFocus, but that just f

3条回答
  •  星月不相逢
    2021-02-04 20:53

    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)

提交回复
热议问题