Person.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Markup.Xaml;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Globalization;
  9. using System.Linq;
  10. using Avalonia.Media;
  11. namespace ControlCatalog.Models
  12. {
  13. public class Person : INotifyDataErrorInfo, INotifyPropertyChanged
  14. {
  15. string _firstName;
  16. string _lastName;
  17. bool _isBanned;
  18. public string FirstName
  19. {
  20. get => _firstName;
  21. set
  22. {
  23. _firstName = value;
  24. if (string.IsNullOrWhiteSpace(value))
  25. SetError(nameof(FirstName), "First Name Required");
  26. else
  27. SetError(nameof(FirstName), null);
  28. OnPropertyChanged(nameof(FirstName));
  29. }
  30. }
  31. public string LastName
  32. {
  33. get => _lastName;
  34. set
  35. {
  36. _lastName = value;
  37. if (string.IsNullOrWhiteSpace(value))
  38. SetError(nameof(LastName), "Last Name Required");
  39. else
  40. SetError(nameof(LastName), null);
  41. OnPropertyChanged(nameof(LastName));
  42. }
  43. }
  44. public bool IsBanned
  45. {
  46. get => _isBanned;
  47. set
  48. {
  49. _isBanned = value;
  50. OnPropertyChanged(nameof(_isBanned));
  51. }
  52. }
  53. Dictionary<string, List<string>> _errorLookup = new Dictionary<string, List<string>>();
  54. void SetError(string propertyName, string error)
  55. {
  56. if (string.IsNullOrEmpty(error))
  57. {
  58. if (_errorLookup.Remove(propertyName))
  59. OnErrorsChanged(propertyName);
  60. }
  61. else
  62. {
  63. if (_errorLookup.TryGetValue(propertyName, out List<string> errorList))
  64. {
  65. errorList.Clear();
  66. errorList.Add(error);
  67. }
  68. else
  69. {
  70. var errors = new List<string> { error };
  71. _errorLookup.Add(propertyName, errors);
  72. }
  73. OnErrorsChanged(propertyName);
  74. }
  75. }
  76. public bool HasErrors => _errorLookup.Count > 0;
  77. public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
  78. public event PropertyChangedEventHandler PropertyChanged;
  79. void OnErrorsChanged(string propertyName)
  80. {
  81. ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
  82. }
  83. void OnPropertyChanged(string propertyName)
  84. {
  85. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  86. }
  87. public IEnumerable GetErrors(string propertyName)
  88. {
  89. if (_errorLookup.TryGetValue(propertyName, out List<string> errorList))
  90. return errorList;
  91. else
  92. return null;
  93. }
  94. }
  95. }