UserMainViewModel.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using AvaloniaApplication1.Models;
  2. using ReactiveUI;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. namespace AvaloniaApplication1.ViewModels
  8. {
  9. public class UserMainViewModel : ViewModelBase
  10. {
  11. private readonly ApiService _apiService;
  12. User user;
  13. List<Gender> genders;
  14. string info;
  15. bool isLoading;
  16. public bool IsLoading { get => isLoading; set => this.RaiseAndSetIfChanged(ref isLoading, value); }
  17. bool isDataLoaded;
  18. public bool IsDataLoaded{ get => isDataLoaded; set => this.RaiseAndSetIfChanged(ref isDataLoaded, value); }
  19. public User CurrentUser
  20. {
  21. get => user; set
  22. {
  23. Info = "";
  24. user = value;
  25. }
  26. }
  27. public string Info { get => info; set => this.RaiseAndSetIfChanged(ref info, value); }
  28. public List<Gender> Genders { get => genders; set => this.RaiseAndSetIfChanged(ref genders, value); }
  29. public Gender selectedGender;
  30. public Gender SelectedGender
  31. {
  32. get => selectedGender; set
  33. {
  34. selectedGender = value;
  35. Info = "";
  36. }
  37. }
  38. public UserMainViewModel(int id)
  39. {
  40. _apiService = new ApiService();
  41. LoadDataAsync(id);
  42. }
  43. private async void LoadDataAsync(int id)
  44. {
  45. IsLoading = true;
  46. IsDataLoaded = false;
  47. try
  48. {
  49. CurrentUser = await _apiService.GetAsync<User>($"getUserById?id={id}");
  50. genders = await _apiService.GetAsync<List<Gender>>("getGenders");
  51. selectedGender = CurrentUser.GenderNavigation;
  52. }
  53. catch (Exception ex)
  54. {
  55. Console.WriteLine($"Îøèáêà ïðè âûçîâå API: {ex.Message}");
  56. }
  57. finally { IsLoading = false; IsDataLoaded = true; }
  58. }
  59. public bool IsNotLoading { get => !IsLoading; }
  60. public DateTimeOffset DateTimeOffset
  61. {
  62. get
  63. {
  64. if (CurrentUser != null)
  65. { new DateTimeOffset(CurrentUser.DateOfBirth, TimeSpan.Zero); }
  66. return DateTimeOffset.Now;
  67. }
  68. set
  69. {
  70. if (CurrentUser != null)
  71. { }
  72. else
  73. {
  74. CurrentUser.DateOfBirth = new DateTime(value.Year, value.Month, value.Day);
  75. Info = "";
  76. }
  77. }
  78. }
  79. public void Save()
  80. {
  81. try
  82. {
  83. myConnection.SaveChanges();
  84. Info = "Äàííûå óñïåøíî ñîõðàíåíû";
  85. }
  86. catch (Exception ex)
  87. {
  88. Info = $"Îøèáêà: {ex.Message}";
  89. }
  90. }
  91. }
  92. }