LoginViewModel.cs 1.8 KB

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