Adding ViewModels

In most cases, Views (Pages) and ViewModels have a one-to-one relationship. However, it is possible for a View (Page) to contain multiple ViewModels or for a ViewModel to be used by multiple Views (Pages). For now, we will simply have a single ViewModel for each Page. Before we create our ViewModels, we will start by creating a base ViewModel class, which will be an abstract class containing the basic functionality that each of our ViewModels will inherit. Initially, the base ViewModel abstract class will only contain a couple of members and wilimplement INotifyPropertyChanged, but we will add to this class as we continue to build upon the TripLog app throughout this book.

In order to create a base ViewModel, perform the following steps:

  1. Create a new abstract class named BaseViewModel in the ViewModels folder using the following code:
      public abstract class BaseViewModel
{
protected BaseViewModel()
{
}
}
  1. Update BaseViewModel to implement INotifyPropertyChanged:
      public abstract class BaseViewModel : INotifyPropertyChanged
{
protected BaseViewModel()
{
}

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(
[CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this,
new PropertyChangedEventArgs(propertyName));

}
}

The implementation of INotifyPropertyChanged is key to the behavior and role of the ViewModels and data binding. It allows a Page to be notified when the properties of its ViewModel have changed.

Now that we have created a base ViewModel, we can start adding the actual ViewModels that will serve as the data context for each of our Pages. We will start by creating a ViewModel for MainPage.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.186.244