Если входные данные недействительны, будет показано окно сообщения и текст в текстовом поле будет отброшен, в противном случае обновите модель.
В ViewModel я использовал метод try...finally в set.
Когда я ввел недопустимое значение в TextBox, появилось окно сообщения, но откат текста не произошел.
Но если бы я использовал try ...catch... наконец-то в методе set был выполнен откат текста.
Вот мой код:
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();
}
}
}
Код: Выделить всё
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
Подробнее здесь: [url]https://stackoverflow.com/questions/78796224/wpf-what-is-difference-between-try-finally-and-try-catch-finally-in-wpf-mv[/url]