Person.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. public string FirstName
  18. {
  19. get => _firstName;
  20. set
  21. {
  22. _firstName = value;
  23. if (string.IsNullOrWhiteSpace(value))
  24. SetError(nameof(FirstName), "First Name Required");
  25. else
  26. SetError(nameof(FirstName), null);
  27. OnPropertyChanged(nameof(FirstName));
  28. }
  29. }
  30. public string LastName
  31. {
  32. get => _lastName;
  33. set
  34. {
  35. _lastName = value;
  36. if (string.IsNullOrWhiteSpace(value))
  37. SetError(nameof(LastName), "Last Name Required");
  38. else
  39. SetError(nameof(LastName), null);
  40. OnPropertyChanged(nameof(LastName));
  41. }
  42. }
  43. Dictionary<string, List<string>> _errorLookup = new Dictionary<string, List<string>>();
  44. void SetError(string propertyName, string error)
  45. {
  46. if (string.IsNullOrEmpty(error))
  47. {
  48. if (_errorLookup.Remove(propertyName))
  49. OnErrorsChanged(propertyName);
  50. }
  51. else
  52. {
  53. if (_errorLookup.TryGetValue(propertyName, out List<string> errorList))
  54. {
  55. errorList.Clear();
  56. errorList.Add(error);
  57. }
  58. else
  59. {
  60. var errors = new List<string> { error };
  61. _errorLookup.Add(propertyName, errors);
  62. }
  63. OnErrorsChanged(propertyName);
  64. }
  65. }
  66. public bool HasErrors => _errorLookup.Count > 0;
  67. public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
  68. public event PropertyChangedEventHandler PropertyChanged;
  69. void OnErrorsChanged(string propertyName)
  70. {
  71. ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
  72. }
  73. void OnPropertyChanged(string propertyName)
  74. {
  75. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  76. }
  77. public IEnumerable GetErrors(string propertyName)
  78. {
  79. if (_errorLookup.TryGetValue(propertyName, out List<string> errorList))
  80. return errorList;
  81. else
  82. return null;
  83. }
  84. }
  85. }