Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Runtime.CompilerServices;
- using FluentValidation;
- using FluentValidation.Attributes;
- using FluentValidation.Results;
- namespace aluTransport.App
- {
- public class ValidatableBindableBase : BindableBase, INotifyDataErrorInfo
- {
- private IValidator Validator => new AttributedValidatorFactory().GetValidator(GetType());
- private readonly Dictionary<string, List<string>> _errors = new Dictionary<string, List<string>>();
- public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged = delegate { };
- public System.Collections.IEnumerable GetErrors(string propertyName)
- {
- if (propertyName == null) return null;
- if (_errors.ContainsKey(propertyName))
- return _errors[propertyName];
- else
- return null;
- }
- //public IList<string> GetAllErrors()
- //{
- // return _errors.SelectMany(err=> err.Value).ToList();
- //}
- public bool HasErrors => _errors.Count > 0;
- protected override void SetProperty<T>(ref T member, T val, [CallerMemberName] string propertyName = null)
- {
- //
- base.SetProperty<T>(ref member, val, propertyName);
- ValidateProperty(propertyName, val);
- }
- private void ValidateProperty<T>(string propertyName, T value)
- {
- ValidationResult results = Validator?.Validate(this);
- if (results == null) return;
- bool validationSucceeded = results.IsValid;
- IList<ValidationFailure> failures = results.Errors;
- if (!validationSucceeded)
- {
- _errors[propertyName] = failures.Where(p=>p.PropertyName == propertyName).Select(c => c.ErrorMessage).ToList();
- }
- else
- {
- _errors.Remove(propertyName);
- }
- ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
- }
- public void ValidateAll()
- {
- ValidationResult results = Validator?.Validate(this);
- if (results == null) return;
- bool validationSucceeded = results.IsValid;
- IList<ValidationFailure> failures = results.Errors;
- if (!validationSucceeded)
- {
- _errors.Clear();
- foreach (var validationFailure in failures)
- {
- _errors[validationFailure.PropertyName] = failures.Where(p => p.PropertyName == validationFailure.PropertyName).Select(c => c.ErrorMessage).ToList();
- ErrorsChanged(this, new DataErrorsChangedEventArgs(validationFailure.PropertyName));
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement