I just posted this up on the MSDN forums, and then worked out the answer myself (so posted my own answer – is that allowed?). Thought it would be good to keep track of for future reference, so here goes…
I’ve got an application where I need to validate a text field as the control loses focus (i.e. as the user thinks (s)he is finished with it), pop up a Message Box informing the user of their error, and then re-focus the TextBox.
My WPF includes (simplified)
<TextBox x:Name=“txText” LostFocus=“txText_LostFocus” /> which calls the following
private void txText_LostFocus(object sender, EventArgs e) { /* Check for valid input */ if (/* not valid */) { MessageBox.Show(“You have entered an incorrect value”); txText.Focus(); } } Problem is, the txText.Focus() line triggers the LostFocus event again, so I end up with a never-ending Message Box loop!
I am aware that I could get around this by using validators and adorners on the TextBox, but I would like the Message Box, and for the TextBox to keep focus if bad data is entered.
There doesn’t seem to be a PreviewLostFocus event – is this correct?
The light came on soon after…
And the answer is… I’m a dope.
Just minutes after posting this question I noticed that there is in fact a PreviewLostKeyboardFocus event. Capturing this event and setting e.Handled = true on an invalid input condition does exactly what I was after. Further, using a KeyboardFocusChangedEventArgs argument in the event handler allows me to check the NewFocus control, and if is equal to (eg) the Cancel button on my dialog, validation can be bypassed.
