LoginViewModel.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Reactive;
  3. using System.Reactive.Linq;
  4. using System.Runtime.Serialization;
  5. using System.Threading.Tasks;
  6. using System.Text;
  7. using ReactiveUI;
  8. using ReactiveUI.Fody.Helpers;
  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 class LoginViewModel : ReactiveObject {
  23. readonly ObservableAsPropertyHelper<int> _usernameLength;
  24. readonly ObservableAsPropertyHelper<int> _passwordLength;
  25. readonly ObservableAsPropertyHelper<bool> _isValid;
  26. public LoginViewModel () {
  27. var canLogin = this.WhenAnyValue (
  28. x => x.Username,
  29. x => x.Password,
  30. (username, password) =>
  31. !string.IsNullOrEmpty (username) &&
  32. !string.IsNullOrEmpty (password));
  33. _isValid = canLogin.ToProperty (this, x => x.IsValid);
  34. Login = ReactiveCommand.CreateFromTask (
  35. () => Task.Delay (TimeSpan.FromSeconds (1)),
  36. canLogin);
  37. _usernameLength = this
  38. .WhenAnyValue (x => x.Username)
  39. .Select (name => name.Length)
  40. .ToProperty (this, x => x.UsernameLength);
  41. _passwordLength = this
  42. .WhenAnyValue (x => x.Password)
  43. .Select (password => password.Length)
  44. .ToProperty (this, x => x.PasswordLength);
  45. Clear = ReactiveCommand.Create (() => { });
  46. Clear.Subscribe (unit => {
  47. Username = string.Empty;
  48. Password = string.Empty;
  49. });
  50. }
  51. [Reactive, DataMember]
  52. public string Username { get; set; } = string.Empty;
  53. [Reactive, DataMember]
  54. public string Password { get; set; } = string.Empty;
  55. [IgnoreDataMember]
  56. public int UsernameLength => _usernameLength.Value;
  57. [IgnoreDataMember]
  58. public int PasswordLength => _passwordLength.Value;
  59. [IgnoreDataMember]
  60. public ReactiveCommand<Unit, Unit> Login { get; }
  61. [IgnoreDataMember]
  62. public ReactiveCommand<Unit, Unit> Clear { get; }
  63. [IgnoreDataMember]
  64. public bool IsValid => _isValid.Value;
  65. }
  66. }