I am trying to set focus of a custom text box on validation error when they are placed next to each other. I have a made a CustomTextBox (Inherits from TextBox) in wpf.

I have to keep two customTextBox one after other in main xaml file.

What do I have to do?

Now on either moving tab or mouse click to outside any other other control or next placed CustomTextBox it must show validation error and should not loose focus if there is error in first one.

Where is the problem?

When I press a tab then it calls LostKeyboardFocus events 2 times. First time for the first CustomTextBox and then next time for the next placed CustomTextBox (I think pressing tab takes it there). I am triggering textbox bindings on LostKeyboardFocusof these custom textboxes and then I check for validation error which already works. And then I popup the error message which work as well

Problem is i have to keep the focus on first CustomTextBox on validation error whereas it is being called again by the next placed CustomTextBox.

My code here is (Only Relevant part):

 public class CustomTextBox : TextBox
    {

       public CustomTextBox()
        {
           this.LostKeyboardFocus += CustomTextBox_LostKeyboardFocus;
        }
      
       private void CustomTextBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            this.Text = updatedText;
            BindingExpression be = this.GetBindingExpression(TextBox.TextProperty);
            if (be == null)
            {
                return;
            }
            be.UpdateSource(); //triggers binding correctly
            if (Validation.GetHasError(this))
            {
                e.Handled = true;
                var errors = Validation.GetErrors(this);// gets validation error
                MainLibrary.ShowErrors(errors[0].Exception); //Popups error window
                Keyboard.Focus(this);
                this.CaretIndex = this.Text.Length;
                return;
            }
        }
    }

How to make this CustomTextBox_LostKeyboardFocus not being called by secondly placed CustomTextBox when there is validation error?

1

There are 1 answers

0
Andy On

When you show a new window, it will activate.

This means it takes focus.

Since only one thing can have focus, anything else you have will lose focus.

Showing errors in a separate new window is a bad idea.

You might be able to mitigate this somewhat by setting showactivated false

<Window ...
     ShowActivated="False">

Except the user can then click on it.

Or they can click on some other control rather than tabbing away from your custom textbox, for that matter.

Which means depending on retaining focus is probably not a good idea.

You might do better forcing entry of only valid data rather than validating. If this is practical for whatever you're doing.