IndeiErrorViewModel.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using ReactiveUI;
  2. using System;
  3. using System.ComponentModel;
  4. using System.Collections;
  5. namespace BindingDemo.ViewModels
  6. {
  7. public class IndeiErrorViewModel : ReactiveObject, INotifyDataErrorInfo
  8. {
  9. private int _maximum = 10;
  10. private int _value;
  11. private string _valueError;
  12. public IndeiErrorViewModel()
  13. {
  14. this.WhenAnyValue(x => x.Maximum, x => x.Value)
  15. .Subscribe(_ => UpdateErrors());
  16. }
  17. public bool HasErrors
  18. {
  19. get { throw new NotImplementedException(); }
  20. }
  21. public int Maximum
  22. {
  23. get { return _maximum; }
  24. set { this.RaiseAndSetIfChanged(ref _maximum, value); }
  25. }
  26. public int Value
  27. {
  28. get { return _value; }
  29. set { this.RaiseAndSetIfChanged(ref _value, value); }
  30. }
  31. public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
  32. public IEnumerable GetErrors(string propertyName)
  33. {
  34. switch (propertyName)
  35. {
  36. case nameof(Value):
  37. return new[] { _valueError };
  38. default:
  39. return null;
  40. }
  41. }
  42. private void UpdateErrors()
  43. {
  44. if (Value <= Maximum)
  45. {
  46. if (_valueError != null)
  47. {
  48. _valueError = null;
  49. ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Value)));
  50. }
  51. }
  52. else
  53. {
  54. if (_valueError == null)
  55. {
  56. _valueError = "Value must be less than Maximum";
  57. ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Value)));
  58. }
  59. }
  60. }
  61. }
  62. }