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?