ModelDataError Class
Base class for models that required the INotifyDataErrorInfo and
INotifyPropertyChanged interfaces.
It's base class is
ModelBase so that functionality is included.
It can be used as a base class, or as an instance variable.
In a class using it as a base class, the protected constructor will be used:
using System.ComponentModel.DataAnnotations;
using Common.Core.Classes;
public class TestModel : ModelDataError
{
public bool IsValid => !HasErrors;
private string? _name;
[Display( Name = "Full Name" )]
[Required( ErrorMessage = "Name cannot be empty." )]
public string Name
{
get => ( _name is not null ) ? _name : string.Empty;
set
{
if( value.Equals( _name ) ) return;
name = value;
ValidateProperty( value );
OnPropertyChanged();
}
}
public TestModel()
{ }
}
In a class using it as an instance variable, the public constructor must be used.
The INotifyDataErrorInfo interface must be implemented and the event handler needs to
subscribe to the core error version so that the ErrorsChanged event is seen as being used:
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Common.Core.Classes;
public class TestModel : INotifyDataErrorInfo
{
public bool IsValid => !_validator.HasErrors;
private string? _name;
[Display( Name = "Full Name" )]
[Required( ErrorMessage = "Name cannot be empty." )]
public string Name
{
get => ( _name is not null ) ? _name : string.Empty;
set
{
if( value.Equals( _name ) ) return;
name = value;
_validator.ValidateProperty( value );
OnPropertyChanged();
}
}
private readonly ModelDataError _validator;
public TestModel()
{
// Do this before anything else
_validator = new ModelDataError( this );
_validator.ErrorsChanged += Core_ErrorsChanged;
}
public bool HasErrors => _validator.HasErrors;
public IEnumerable GetErrors( string? propertyName )
{
return _validator.GetErrors( propertyName );
}
public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
private void Core_ErrorsChanged( object? sender, DataErrorsChangedEventArgs e )
{
ErrorsChanged?.Invoke( this, e );
}
}
HasErrors | Gets a value that indicates whether the entity has validation errors. |
ClearErrors | Clears the validation errors for a specified property or for the entire entity. |
GetErrors | Gets the validation errors for a specified property or for the entire entity. |
ValidateAllProperties | Validates all the properties in the current instance. |
ValidateProperty | Validates a property with a specified name and a given input value. |
ErrorsChanged | Occurs when the validation errors have changed for a property or for the entire entity. |