LoginViewModel.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. //
  10. // This view model can be easily shared across different UI frameworks.
  11. // For example, if you have a WPF or XF app with view models written
  12. // this way, you can easily port your app to Terminal.Gui by implementing
  13. // the views with Terminal.Gui classes and ReactiveUI bindings.
  14. //
  15. // We mark the view model with the [DataContract] attributes and this
  16. // allows you to save the view model class to the disk, and then to read
  17. // the view model from the disk, making your app state persistent.
  18. // See also: https://www.reactiveui.net../docs/handbook/data-persistence/
  19. //
  20. [DataContract]
  21. public class LoginViewModel : ReactiveObject {
  22. readonly ObservableAsPropertyHelper<int> _usernameLength;
  23. readonly ObservableAsPropertyHelper<int> _passwordLength;
  24. readonly ObservableAsPropertyHelper<bool> _isValid;
  25. public LoginViewModel () {
  26. var canLogin = this.WhenAnyValue (
  27. x => x.Username,
  28. x => x.Password,
  29. (username, password) =>
  30. !string.IsNullOrEmpty (username) &&
  31. !string.IsNullOrEmpty (password));
  32. _isValid = canLogin.ToProperty (this, x => x.IsValid);
  33. Login = ReactiveCommand.CreateFromTask<EventArgs> (
  34. e => Task.Delay (TimeSpan.FromSeconds (1)),
  35. canLogin);
  36. _usernameLength = this
  37. .WhenAnyValue (x => x.Username)
  38. .Select (name => name.Length)
  39. .ToProperty (this, x => x.UsernameLength);
  40. _passwordLength = this
  41. .WhenAnyValue (x => x.Password)
  42. .Select (password => password.Length)
  43. .ToProperty (this, x => x.PasswordLength);
  44. Clear = ReactiveCommand.Create<EventArgs> (e => { });
  45. Clear.Subscribe (unit => {
  46. Username = string.Empty;
  47. Password = string.Empty;
  48. });
  49. }
  50. [Reactive, DataMember]
  51. public string Username { get; set; } = string.Empty;
  52. [Reactive, DataMember]
  53. public string Password { get; set; } = string.Empty;
  54. [IgnoreDataMember]
  55. public int UsernameLength => _usernameLength.Value;
  56. [IgnoreDataMember]
  57. public int PasswordLength => _passwordLength.Value;
  58. [IgnoreDataMember]
  59. public ReactiveCommand<EventArgs, Unit> Login { get; }
  60. [IgnoreDataMember]
  61. public ReactiveCommand<EventArgs, Unit> Clear { get; }
  62. [IgnoreDataMember]
  63. public bool IsValid => _isValid.Value;
  64. }
  65. }