I've very simple check if there are validation error somewhere in my window (assuming what all bindings will have NotifyOnValidationError set):
public MainWindow()
{
InitializeComponent();
DataContext = new VM();
AddHandler(Validation.ErrorEvent, new RoutedEventHandler((s, e) =>
{
var args = (ValidationErrorEventArgs)e;
var binding = (BindingExpression)args.Error.BindingInError;
Title = binding.HasError ? $"Error {args.Error.ErrorContent}" : "";
}), true);
}
The event is rised when errors appear/disappear, but for some reasons HasError still true when there are no more errors and ErrorContent contains old error text.
What am I doing wrong?
Below is a simple MCVE with validation that Test should be 0.
Binding errors (entering 0a or empty string) are set/reset correctly. Validation error is set correctly (when entering 1), but is not reset (when entering 0). Why?
Implementing INotifyPropertyChange makes no difference.
xaml:
<TextBox Text="{Binding Test, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}" />
View Model:
public class VM : INotifyDataErrorInfo
{
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
int _test;
public int Test
{
get => _test;
set
{
_test = value;
_error = value == 0 ? null : "Must be 0";
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Test)));
}
}
string _error;
public bool HasErrors => _error != null;
public IEnumerable GetErrors(string propertyName)
{
if (_error != null)
yield return _error;
}
}
