How to determine if there are no errors anymore in Validation.ErrorEvent?

Viewed 94

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;
    }

}
1 Answers

If you set the Title from within the handler, I think you need to consider the ValidationErrorEventArgs.Action Property:

Gets a value that indicates whether the error is a new error or an existing error that has now been cleared.

I am not 100% sure, but I suspect that by the time you check the HasError Property, it has not yet been cleared. (Suspicion based on "Also note that a valid value transfer in either direction (target-to-source or source-to-target) clears the Validation.Errorsattached property." from MSDN)

Related