LoginViewModel.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Reactive;
  3. using System.Reactive.Linq;
  4. using System.Runtime.Serialization;
  5. using System.Threading.Tasks;
  6. using ReactiveUI;
  7. using ReactiveUI.Fody.Helpers;
  8. namespace ReactiveExample {
  9. [DataContract]
  10. public class LoginViewModel : ReactiveObject {
  11. readonly ObservableAsPropertyHelper<int> _usernameLength;
  12. readonly ObservableAsPropertyHelper<int> _passwordLength;
  13. readonly ObservableAsPropertyHelper<bool> _isValid;
  14. public LoginViewModel () {
  15. var canLogin = this.WhenAnyValue (
  16. x => x.Username,
  17. x => x.Password,
  18. (username, password) =>
  19. !string.IsNullOrWhiteSpace (username) &&
  20. !string.IsNullOrWhiteSpace (password));
  21. _isValid = canLogin.ToProperty (this, x => x.IsValid);
  22. Login = ReactiveCommand.CreateFromTask (
  23. () => Task.Delay (TimeSpan.FromSeconds (1)),
  24. canLogin);
  25. _usernameLength = this
  26. .WhenAnyValue (x => x.Username)
  27. .Select (name => name.Length)
  28. .ToProperty (this, x => x.UsernameLength);
  29. _passwordLength = this
  30. .WhenAnyValue (x => x.Password)
  31. .Select (password => password.Length)
  32. .ToProperty (this, x => x.PasswordLength);
  33. }
  34. [Reactive, DataMember]
  35. public string Username { get; set; } = string.Empty;
  36. [Reactive, DataMember]
  37. public string Password { get; set; } = string.Empty;
  38. [IgnoreDataMember]
  39. public int UsernameLength => _usernameLength.Value;
  40. [IgnoreDataMember]
  41. public int PasswordLength => _passwordLength.Value;
  42. [IgnoreDataMember]
  43. public ReactiveCommand<Unit, Unit> Login { get; }
  44. [IgnoreDataMember]
  45. public bool IsValid => _isValid.Value;
  46. }
  47. }