Up to this point, we have mainly prepared to write the code that will make up the app itself. MainViewModel is the ViewModel class for the first view that is displayed to the user. It is responsible for providing data and logic to a list of to-do list items. We will create the bare-bones ViewModel classes and add code to them as we progress through this chapter:
- Create a class called MainViewModel in the ViewModels folder.
- Add the following template code and resolve the references:
public class MainViewModel : ViewModel
{
private readonly TodoItemRepository repository;
public MainViewModel(TodoItemRepository repository)
{
this.repository = repository;
Task.Run(async () => await LoadData());
}
private async Task LoadData()
{
}
}
The structure of this class is something that we will reuse for all the ViewModel classes to come.
Let's summarize the important features we want the ViewModel class to have:
- We inherit from the ViewModel class to gain access to shared logic, such as the INotifyPropertyChanged interface and common navigation code.
- All dependencies to other classes, such as repositories and services, are passed through the constructor of ViewModel. This is handled by the dependency injection pattern and, more specifically for our case, by Autofac, which is the implementation of the dependency injection we are using.
- We use an asynchronous call to LoadData() as an entry point to initialize the ViewModel class. Different MVVM libraries might do this in different ways, but the basic functionally is the same.