TodoListViewModel.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.ComponentModel;
  5. using System.Runtime.CompilerServices;
  6. using System.Threading.Tasks;
  7. using Xamarin.Forms;
  8. namespace DevDaysTasks
  9. {
  10. public class TodoListViewModel : INotifyPropertyChanged
  11. {
  12. TodoItemManager manager;
  13. public TodoListViewModel()
  14. {
  15. manager = TodoItemManager.DefaultManager;
  16. Items = new ObservableCollection<TodoItem>();
  17. AddCommand = new Command(async () => await AddAsync());
  18. CompleteCommand = new Command<TodoItem>(async (item) => await CompleteAsync(item));
  19. SyncCommand = new Command(async () => await RefreshAsync(true));
  20. RefreshCommand = new Command(async () => await RefreshAsync(false));
  21. }
  22. ObservableCollection<TodoItem> items;
  23. public ObservableCollection<TodoItem> Items
  24. {
  25. get { return items; }
  26. set { items = value; OnPropertyChanged(); }
  27. }
  28. string name;
  29. public string Name
  30. {
  31. get { return name; }
  32. set { name = value; OnPropertyChanged(); }
  33. }
  34. bool busy;
  35. public bool IsBusy
  36. {
  37. get { return busy; }
  38. set { busy = value; OnPropertyChanged(); }
  39. }
  40. public Command AddCommand { get; }
  41. async Task AddAsync()
  42. {
  43. IsBusy = true;
  44. var item = new TodoItem { Name = Name };
  45. await manager.SaveTaskAsync(item);
  46. Items = await manager.GetTodoItemsAsync();
  47. Name = string.Empty;
  48. IsBusy = false;
  49. }
  50. public Command<TodoItem> CompleteCommand { get; }
  51. public async Task CompleteAsync(TodoItem item)
  52. {
  53. IsBusy = true;
  54. item.Done = true;
  55. await manager.SaveTaskAsync(item);
  56. Items = await manager.GetTodoItemsAsync();
  57. IsBusy = false;
  58. }
  59. public Command SyncCommand { get; }
  60. public Command RefreshCommand { get; }
  61. async Task RefreshAsync(bool? sync)
  62. {
  63. IsBusy = true;
  64. try
  65. {
  66. Items = await manager.GetTodoItemsAsync(sync.HasValue && sync.Value);
  67. }
  68. catch (Exception ex)
  69. {
  70. await Application.Current.MainPage.DisplayAlert("Refresh Error", "Couldn't refresh data (" + ex.Message + ")", "OK");
  71. }
  72. finally
  73. {
  74. IsBusy = false;
  75. }
  76. }
  77. public event PropertyChangedEventHandler PropertyChanged;
  78. void OnPropertyChanged([CallerMemberName]string name = "")
  79. => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
  80. }
  81. }