LoginViewModel.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.ComponentModel;
  3. using System.Reactive;
  4. using System.Reactive.Linq;
  5. using System.Runtime.Serialization;
  6. using System.Threading.Tasks;
  7. using ReactiveUI;
  8. using ReactiveUI.SourceGenerators;
  9. namespace ReactiveExample;
  10. //
  11. // This view model can be easily shared across different UI frameworks.
  12. // For example, if you have a WPF or XF app with view models written
  13. // this way, you can easily port your app to Terminal.Gui by implementing
  14. // the views with Terminal.Gui classes and ReactiveUI bindings.
  15. //
  16. // We mark the view model with the [DataContract] attributes and this
  17. // allows you to save the view model class to the disk, and then to read
  18. // the view model from the disk, making your app state persistent.
  19. // See also: https://www.reactiveui.net../docs/handbook/data-persistence/
  20. //
  21. [DataContract]
  22. public partial class LoginViewModel : ReactiveObject
  23. {
  24. [IgnoreDataMember]
  25. [ObservableAsProperty] private bool _isValid;
  26. [IgnoreDataMember]
  27. [ObservableAsProperty] private int _passwordLength;
  28. [IgnoreDataMember]
  29. [ObservableAsProperty] private int _usernameLength;
  30. [DataMember]
  31. [Reactive] private string _password = string.Empty;
  32. [DataMember]
  33. [Reactive] private string _username = string.Empty;
  34. public LoginViewModel ()
  35. {
  36. InitializeCommands ();
  37. IObservable<bool> canLogin = this.WhenAnyValue
  38. (
  39. x => x.Username,
  40. x => x.Password,
  41. (username, password) =>
  42. !string.IsNullOrEmpty (username) && !string.IsNullOrEmpty (password)
  43. );
  44. _isValidHelper = canLogin.ToProperty (this, x => x.IsValid);
  45. Login = ReactiveCommand.CreateFromTask<HandledEventArgs>
  46. (
  47. e => Task.Delay (TimeSpan.FromSeconds (1)),
  48. canLogin
  49. );
  50. _usernameLengthHelper = this
  51. .WhenAnyValue (x => x.Username)
  52. .Select (name => name.Length)
  53. .ToProperty (this, x => x.UsernameLength);
  54. _passwordLengthHelper = this
  55. .WhenAnyValue (x => x.Password)
  56. .Select (password => password.Length)
  57. .ToProperty (this, x => x.PasswordLength);
  58. ClearCommand.Subscribe (
  59. unit =>
  60. {
  61. Username = string.Empty;
  62. Password = string.Empty;
  63. }
  64. );
  65. }
  66. [ReactiveCommand]
  67. public void Clear (HandledEventArgs args) { }
  68. [IgnoreDataMember]
  69. public ReactiveCommand<HandledEventArgs, Unit> Login { get; }
  70. }