Xamarin.Forms Projects
上QQ阅读APP看书,第一时间看更新

Creating the MainViewModel

Up to this point, we have mainly been preparing to write the code that will make up the app itself. The MainViewModel is the ViewModel for the first view that will be displayed to the user. It will be responsible for providing data and logic to a list of to-do list items. We will create the bare-bones ViewModels and add code to them as we move through the chapter:

  1. Create a class called MainViewModel inside the ViewModels folder.
  2. 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 in this class is something that we will reuse for all the ViewModels to come.

Let's summarize the important features we want the ViewModel to have:

  • We inherit from the ViewModel 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 the ViewModel. This will be handled by the dependency injection pattern and, more specifically for our case, by Autofac, which is the implementation of dependency injection we are using.
  • We use an asynchronous call to LoadData() as an entry point to initialize the ViewModel. Different MVVM libraries might do this in different ways, but the basic functionally is the same.