I’m using a custom TextBox to validate input value.
If the input data was invalid, a message box would be shown and the Text in TextBox would be rollback, else update the Model .
In the ViewModel, I used try…finally in set method.
When I entered an invalid value to TextBox, the message box appeared but the Text didn’t be rollback.
But if I used try…catch…finally in set method the Text was rollback.
Here is my code:
ViewModel.cs.
public Value
{
get => _model.Value;
set
{
try {
_model.Value = value;
// Some codes
}
catch(Exception) // What's the situation with the catch?
{
}
finally
{
OnPropertyChanged();
}
}
}
XAML:
<commonControls:IntegerBox Text="{Binding Path=Value, UpdateSourceTrigger=Explicit, Mode=TwoWay}"
OnLostFocusInvalidValueCommand="{Binding NumericBoxLostFocusCommand}"
>
</commonControls:IntegerBox>
The NumericBoxLostFocusCommand just show the message box.
IntegerBox.cs:
public static readonly DependencyProperty IsValidProperty =
DependencyProperty.Register(
nameof(IsValid),
typeof(bool),
typeof(IntegerBox),
new PropertyMetadata(true));
public bool IsValid
{
get => (bool)GetValue(IsValidProperty);
set => SetValue(IsValidProperty, value);
}
public IntegerBox()
{
PreviewTextInput += NumericBox_PreviewTextInput;
TextChanged += NumericBox_TextChanged;
LostFocus += Numeric_LostFocus;
}
protected virtual void Numeric_LostFocus(object sender, RoutedEventArgs e)
{
if (sender is TextBox textBox)
{
if (!IsValid)
{
OnLostFocusInvalidValueCommand?.Execute(sender);
}
var bindingExpression = BindingOperations.GetBindingExpression(textBox, TextBox.TextProperty);
bindingExpression?.UpdateSource();
if (IsValid)
{
OnLostFocusValidateValueCommand?.Execute(null);
}
}
}
protected override void NumericBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (Text.IsNullOrWhiteSpace() && !Nullable)
{
IsValid = false;
ToolTip = ErrorMessages.ERR_EMPTY_INPUT;
}
if (MaxValue > MinValue && int.TryParse(Text, out var currentInteger))
{
IsValid = currentInteger >= MinValue && currentInteger <= MaxValue;
}
}
protected override void NumericBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsTextAllowed(e.Text);
}
private bool IsTextAllowed(string text)
{
return !_integerRegex.IsMatch(text);
}
Why is there a difference between using and not the catch block?
I tried add the catch block to set method.