IndeiErrorViewModel.cs 2.0 KB

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