1+ // Licensed to the .NET Foundation under one or more agreements.
2+ // The .NET Foundation licenses this file to you under the MIT license.
3+ // See the LICENSE file in the project root for more information.
4+
5+ using ClientApp . Interfaces ;
6+ using ClientApp . Models ;
7+ using CommunityToolkit . Mvvm . ComponentModel ;
8+ using CommunityToolkit . Mvvm . Input ;
9+ using System . ComponentModel ;
10+
11+ namespace ClientApp . ViewModels ;
12+
13+ public partial class TodoListViewModel ( ITodoService todoService , IAlertService alertService ) : ObservableRecipient
14+ {
15+ [ ObservableProperty ]
16+ private bool isRefreshing ;
17+
18+ [ ObservableProperty ]
19+ private BindingList < TodoItem > items = [ ] ;
20+
21+ [ ObservableProperty ]
22+ private string addItemTitle = string . Empty ;
23+
24+ [ RelayCommand ]
25+ public async Task AddItemAsync ( CancellationToken cancellationToken = default )
26+ {
27+ try
28+ {
29+ var addition = await todoService . AddTodoItemAsync ( AddItemTitle , cancellationToken ) ;
30+ Items . Add ( addition ) ;
31+ AddItemTitle = string . Empty ;
32+ }
33+ catch ( Exception ex )
34+ {
35+ await alertService . ShowErrorAlertAsync ( "Error adding item" , ex . Message ) ;
36+ }
37+ }
38+
39+ [ RelayCommand ]
40+ public async Task UpdateItemAsync ( TodoItem item , CancellationToken cancellationToken = default )
41+ {
42+ try
43+ {
44+ TodoItem ? storedItem = await todoService . GetTodoItemAsync ( item . Id , cancellationToken ) ;
45+ if ( storedItem is not null )
46+ {
47+ storedItem . IsComplete = ! storedItem . IsComplete ;
48+ var replacedItem = await todoService . ReplaceTodoItemAsync ( storedItem , cancellationToken ) ;
49+ var idx = Items . IndexOf ( item ) ;
50+ Items [ idx ] = replacedItem ;
51+ }
52+ else
53+ {
54+ await alertService . ShowErrorAlertAsync ( "Item not found" , "The item was not found in the database." ) ;
55+ }
56+ }
57+ catch ( Exception ex )
58+ {
59+ await alertService . ShowErrorAlertAsync ( "Error updating item" , ex . Message ) ;
60+ }
61+ }
62+
63+ [ RelayCommand ]
64+ public async Task RefreshItemsAsync ( CancellationToken cancellationToken = default )
65+ {
66+ try
67+ {
68+ IsRefreshing = true ;
69+ List < TodoItem > dbItems = await todoService . GetAllTodoItemsAsync ( cancellationToken ) ;
70+ Items . Clear ( ) ;
71+ foreach ( var dbItem in dbItems )
72+ {
73+ Items . Add ( dbItem ) ;
74+ }
75+ }
76+ catch ( Exception ex )
77+ {
78+ await alertService . ShowErrorAlertAsync ( "Error refreshing items" , ex . Message ) ;
79+ }
80+ finally
81+ {
82+ IsRefreshing = false ;
83+ }
84+ }
85+ }
0 commit comments