I have a databound TextBox in my application like so: (The type of Height is decimal?)
<TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True, Converter={StaticResource NullConverter}}" />
public class NullableConverter : IValueConverter { public object Convert(object o, Type type, object parameter, CultureInfo culture) { return o; } public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) { if (o as string == null || (o as string).Trim() == string.Empty) return null; return o; } }
Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either:
- Not allow the TextBox to lose focus until it contains a valid value.
- Revert the value in the TextBox to the last valid value.
What is the best way to do this?
Update:
I’ve found a way to do #2. I don’t love it, but it works:
private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) { var box = sender as TextBox; var binding = box.GetBindingExpression(TextBox.TextProperty); if (binding.HasError) binding.UpdateTarget(); }
Does anyone know how to do this better? (Or do #1.)
You can force the keyboard focus to stay on the
TextBoxby handling thePreviewLostKeyBoardFocusevent like this: