Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
strauss_d_getting_started_with_visual_studio_2022_learning_a.pdf
Скачиваний:
123
Добавлен:
26.06.2023
Размер:
17.04 Mб
Скачать

Chapter 2 Working with Visual Studio 2022

As seen in Listing 2-13, the service is really straightforward. By adding the SQLite namespace via the using statement, we can create a SQLiteAsyncConnection object that accepts a path to the database file called mydb.db. The Init method checks to see if the database exists and, if not, creates the database with the todo table from the ToDoItem. Because the SQLite connection is asynchronous, we can call the InsertAsync and ToListAsync methods to insert and get to-do items.

The MainViewModel

The MainViewModel provides an ObservableCollection of ToDoItem and creates an ObservableProperty for the isRefreshing field, as seen in Listing 2-14. This way, if the collection of to-do items is busy being refreshed, we can control that if the user clicks the refresh button multiple times.

Listing 2-14.  The MainViewModel Class

using System.Collections.ObjectModel; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input;

using HelloMAUI.Model; using HelloMAUI.Services;

namespace HelloMAUI.ViewModel

{

public partial class MainViewModel : ObservableObject

{

readonly IToDoService _service;

public ObservableCollection<ToDoItem> ToDoItems { get; set; } = new();

[ObservableProperty] bool isRefreshing;

public MainViewModel(IToDoService service)

{

_service = service;

}

101

Chapter 2 Working with Visual Studio 2022

[RelayCommand] async Task AddTodo()

{

var item = await Application.Current.MainPage.Display PromptAsync("To Do Item", "Enter To-Do Item.", "Add", "Cancel"); if (item != null)

{

await _service.AddToDo(item); await Refresh();

}

}

[RelayCommand]

async Task GetAllTodoItems()

{

if (IsRefreshing) return;

var todoItems = await _service.GetToDoItems();

if (todoItems.Count() > 0) ToDoItems.Clear();

foreach (var item in todoItems)

{

var todo = new ToDoItem()

{

ToDoText = item.ToDoText, Id = item.Id

};

ToDoItems.Add(todo);

}

}

[RelayCommand] async Task Refresh()

{

102

Chapter 2 Working with Visual Studio 2022

if (!IsRefreshing)

{

IsRefreshing = true; ToDoItems.Clear();

var todoItems = await _service.GetToDoItems();

foreach (var item in todoItems)

{

var todo = new ToDoItem()

{

ToDoText = item.ToDoText, Id = item.Id

};

ToDoItems.Add(todo);

}

IsRefreshing = false;

}

}

}

}

Again, the code in the view model is relatively straightforward. We use dependency injection to inject our ToDo Service via the constructor. We then set up the methods to add to-do items, read to-do items, and refresh the to-do items to act as commands by adding the [RelayCommand] attribute to each one. These allow us to use our ToDo Service to add and read items from SQLite. The last thing we need to do is register the service dependencies with the IServiceCollection.

Registering Dependencies

The services are registered in the MauiProgram class by adding them as Singletons to the IServiceCollection, as seen in Listing 2-15.

103

Chapter 2 Working with Visual Studio 2022

Listing 2-15.  Registering the Services

using HelloMAUI.Services; using HelloMAUI.ViewModel;

namespace HelloMAUI;

public static class MauiProgram

{

public static MauiApp CreateMauiApp()

{

var builder = MauiApp.CreateBuilder(); builder

.UseMauiApp<App>()

.ConfigureFonts(fonts =>

{

fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");

});

builder.Services.AddSingleton<IToDoService, ToDoService>(); builder.Services.AddSingleton<MainViewModel>(); builder.Services.AddSingleton<MainPage>();

return builder.Build();

}

}

We are telling our application that whenever something requests IToDoService, give it the ToDoService class that contains the implementation for our IToDoService

Interface. This loose coupling allows us to easily swap out the implementation contained in the ToDoService class and replace it with another implementation. We have now registered our page (MainPage), our view model (MainViewModel), and our to-do service (IToDoService) with the IServiceCollection. We can now go ahead and start building the UI for our application.

104