Skip to content

Instantly share code, notes, and snippets.

@zetroot
Created September 21, 2020 14:06
Show Gist options
  • Save zetroot/6b4816d9c3b7ba9e6f33e9a7a53b4ee3 to your computer and use it in GitHub Desktop.
Save zetroot/6b4816d9c3b7ba9e6f33e9a7a53b4ee3 to your computer and use it in GitHub Desktop.
NotifyDataErrorInfo
public class NotifyDataErrorInfo : INotifyPropertyChanged, INotifyDataErrorInfo
{
private readonly Dictionary<string, List<string>> _errorsByPropertyName = new Dictionary<string, List<string>>();
private readonly Func<IdentityUserVM, bool> PropertyUniquityValidationCallback;
private string property;
public string Property
{
get => base.UserName;
set
{
property = value;
OnPropertyChanged();
ValidateUserName();
}
}
private void ValidateProperty()
{
ClearErrors(nameof(Property));
if (string.IsNullOrWhiteSpace(Property))
AddError(nameof(Property), "ololo pysch pysch");
if(!PropertyUniquityValidationCallback(this))
AddError(nameof(Property), "upchck");
}
#region notify property changed
/// <inheritdoc/>
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName]string prop = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
#endregion
#region notify on errors
private void OnErrorsChanged(string propertyName) => ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
/// <inheritdoc/>
public bool HasErrors => _errorsByPropertyName.Any();
/// <inheritdoc/>
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
/// <inheritdoc/>
public IEnumerable GetErrors(string propertyName)
{
if (string.IsNullOrWhiteSpace(propertyName))
return _errorsByPropertyName.Values.SelectMany(x => x);
return _errorsByPropertyName.ContainsKey(propertyName) ? _errorsByPropertyName[propertyName] : null;
}
private void AddError(string propertyName, string error)
{
if (!_errorsByPropertyName.ContainsKey(propertyName))
_errorsByPropertyName[propertyName] = new List<string>();
if (!_errorsByPropertyName[propertyName].Contains(error))
{
_errorsByPropertyName[propertyName].Add(error);
OnErrorsChanged(propertyName);
}
}
private void ClearErrors(string propertyName)
{
if (_errorsByPropertyName.ContainsKey(propertyName))
{
_errorsByPropertyName.Remove(propertyName);
OnErrorsChanged(propertyName);
}
}
#endregion
public NotifyDataErrorInfo(Func<NotifyDataErrorInfo, bool> propertyUniquityValidationCallback)
{
PropertyUniquityValidationCallback = propertyUniquityValidationCallback ?? throw new ArgumentNullException(nameof(propertyUniquityValidationCallback));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment