ValidationTemplate.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel.DataAnnotations;
  5. using System.ComponentModel;
  6. using System.Linq;
  7. namespace LogoForceTestApp.Modules.MainModule
  8. {
  9. public class ValidationTemplate : IDataErrorInfo, INotifyDataErrorInfo
  10. {
  11. readonly INotifyPropertyChanged _target;
  12. readonly ValidationContext _validationContext;
  13. readonly List<ValidationResult> _validationResults;
  14. public ValidationTemplate(INotifyPropertyChanged target)
  15. {
  16. this._target = target;
  17. _validationContext = new ValidationContext(target, null, null);
  18. _validationResults = new List<ValidationResult>();
  19. Validator.TryValidateObject(target, _validationContext, _validationResults, true);
  20. target.PropertyChanged += Validate;
  21. }
  22. void Validate(object sender, PropertyChangedEventArgs e)
  23. {
  24. _validationResults.Clear();
  25. Validator.TryValidateObject(_target, _validationContext, _validationResults, true);
  26. var hashSet = new HashSet<string>(_validationResults.SelectMany(x => x.MemberNames));
  27. foreach (var error in hashSet)
  28. {
  29. RaiseErrorsChanged(error);
  30. }
  31. }
  32. public IEnumerable GetErrors(string propertyName)
  33. {
  34. return _validationResults.Where(x => x.MemberNames.Contains(propertyName))
  35. .Select(x => x.ErrorMessage);
  36. }
  37. public bool HasErrors
  38. {
  39. get { return _validationResults.Count > 0; }
  40. }
  41. public string Error
  42. {
  43. get
  44. {
  45. var strings = _validationResults.Select(x => x.ErrorMessage)
  46. .ToArray();
  47. return string.Join(Environment.NewLine, strings);
  48. }
  49. }
  50. public string this[string propertyName]
  51. {
  52. get
  53. {
  54. var strings = _validationResults.Where(x => x.MemberNames.Contains(propertyName))
  55. .Select(x => x.ErrorMessage)
  56. .ToArray();
  57. return string.Join(Environment.NewLine, strings);
  58. }
  59. }
  60. public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
  61. void RaiseErrorsChanged(string propertyName)
  62. {
  63. ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
  64. }
  65. }
  66. }