In this section, we will begin by creating a base MVVM ViewModel that will be used by each of our ViewModels when we create these, the Views (pages) will then implement those ViewModels and use them as their BindingContext
.
Let's take a look at how we can achieve this, by following these steps:
ViewModels
folder, shown in the following screenshot:
WalkBaseViewModel
for the name of the new class file to be created, as shown in the following screenshot:
Up until this point, all we have done is create our WalkBaseViewModel
class file. This abstract class will act as the base ViewModel class that will contain the basic functionality that each of our ViewModels will inherit from.
As we start to build the base class, you will see that it contains a couple of members and it will implement the INotifyPropertyChangedInterface
. As we progress through this book, we will build to this class, which will be used by the TrackMyWalks
application. To proceed with creating the base ViewModel class.
Ensure that the WalkBaseViewModel.cs
file is displayed within the code editor, and enter in the following code snippet:
// // WalkBaseViewModel.cs // TrackMyWalks Base ViewModel // // Created by Steven F. Daniel on 22/08/2016. // Copyright © 2016 GENIESOFT STUDIOS. All rights reserved. // using System.ComponentModel; using System.Runtime.CompilerServices; namespace TrackMyWalks.ViewModels { public abstract class WalkBaseViewModel : INotifyPropertyChanged { protected WalkBaseViewModel() { } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged ([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } }
In the preceding code snippet, we begin by creating a new abstract
class for our WalkBaseViewModel
that implements from the INotifyPropertyChanged
interface class, which allows the View or page to be notified whenever properties contained within the ViewModel have changed. Next, we declare a variable PropertyChanged
that inherits from the PropertyChanged
EventHandler
that will be used to indicate whenever properties on the object have changed. Finally, within the OnPropertyChanged
method, this will be called when it has determined that a change has occurred on a property within the ViewModel from a child class.
3.145.11.227