LoginViewModel.cs 2.6 KB

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