LoginViewModel.cs 1.8 KB

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