Thursday, July 10, 2014

Undoing a LostFocus event

I have a requirement to detect an invalid value as a user tabs off a textbox, display a messagebox, reset the value in the textbox, and move focus back to the textbox.

The obvious solution is to handle the LostFocus event. My first attempt at this is shown below

Private Sub OverallDiscountPercentTextBox_LostFocus(sender As System.Object, e As System.Windows.RoutedEventArgs) Dim OverallDiscountAmount As Decimal = 0 Decimal.TryParse(OverallDiscountPercentTextBox.Text, OverallDiscountPercent) If OverallDiscountPercent > 100 Then MessageBox.Show("Discount cannot be more than 100%.", "Discount Error", MessageBoxButton.OK, MessageBoxImage.Error) OverallDiscountPercentTextBox.Text = 0.ToString("F2") OverallDiscountPercentTextBox.Focus Exit Sub End If ... End Sub
This does not move the focus back to the textbox. Clearly the framework has not finished moving the focus to the next control when the LostFocus event is raised. I suppose this doesn't happen until the next control's Focus event is raised.

The solution is fairly simple once you understand how to write lambda functions in Visual Basic. You defer the Focus method like this...

Dispatcher.BeginInvoke(Function() OverallDiscountPercentTextBox.Focus(), Windows.Threading.DispatcherPriority.Background)

No comments:

Post a Comment