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

I mixed up with PreviewLostKeyboardFocusthat almost came to you. I saw a couple of implementations using LostFocus, but it just makes the focus return to TextBoxafter losing focus, and you can easily see this offset on the screen. Basically, I'm just looking for the same type of behavior that you could use with help OnValidatingin WinForms.

+5
source share
3 answers

In my opinion, the best way, as a rule, is not to do this. It is almost always better to simply turn off other controls or prevent saving until the value is valid.

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

  • Intercept the version of keyboard and mouse events Previewat the level of your window or any area in which you want to prevent focus changes inside (for example, maybe not in the menu bar).

  • When a Key Key Key or Tune KeyDown event is detected in a text field or when MouseDown is detected outside the text field when it has focus, call UpdateSource () in the binding expression, then check faileded Handled = true to prevent further use of the KeyDown or MouseDown event .

  • PreviewLostKeyboardFocus, , , .

+5

Ray:

UpdateSource :

BindingExpression be = userTextbox.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();

, :

UpdateSourceTrigger = "PropertyChanged";

, , ().

+2

LostFocus, StackOverflowException, ( , ), : .

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 can make sure that focus recovery does not interfere with the current focus (and avoid an unpleasant exception that you would otherwise encounter)

+1
source

All Articles