LoginViewModel.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. IObservable<bool> canLogin = this.WhenAnyValue
  37. (
  38. x => x.Username,
  39. x => x.Password,
  40. (username, password) =>
  41. !string.IsNullOrEmpty (username) && !string.IsNullOrEmpty (password)
  42. );
  43. _isValidHelper = canLogin.ToProperty (this, x => x.IsValid);
  44. Login = ReactiveCommand.CreateFromTask<HandledEventArgs>
  45. (
  46. e => Task.Delay (TimeSpan.FromSeconds (1)),
  47. canLogin
  48. );
  49. _usernameLengthHelper = this
  50. .WhenAnyValue (x => x.Username)
  51. .Select (name => name.Length)
  52. .ToProperty (this, x => x.UsernameLength);
  53. _passwordLengthHelper = this
  54. .WhenAnyValue (x => x.Password)
  55. .Select (password => password.Length)
  56. .ToProperty (this, x => x.PasswordLength);
  57. ClearCommand.Subscribe (
  58. unit =>
  59. {
  60. Username = string.Empty;
  61. Password = string.Empty;
  62. }
  63. );
  64. }
  65. [ReactiveCommand]
  66. public void Clear (HandledEventArgs args) { }
  67. [IgnoreDataMember]
  68. public ReactiveCommand<HandledEventArgs, Unit> Login { get; }
  69. }