ViewModel, we need to have some values that are used to bind to the controls on the UI. Now create a new folder called
ViewModelsand create a new class called
FirstViewModel.cswhich inherits from the
MvxViewModelis a base class to encapsulate some essential features of the
ViewModel, such as the
INotifyPropertyChangedinterface and the lifecycle of the page.
INotifyPropertyChangedis the important interface when using data-binding, which can notify the clients that a property value has changed. You can get more details about this interface here: https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged?view=netframework-4.7.2 . If we implement this interface by ourselves, you might feel that it is a little bit tedious. With this base class -
MvxViewModel, we can easily create the properties that supports data-binding. Also, it exposes necessary lifecycle events to allow us to inject the handler to the specific lifecycle events. I created a code snippet to simplify the property inputs. You can find it here: https://github.com/yanxiaodi/MvvmCrossDemo/blob/dev/MvvmCrossDemo/Resources/CodeSnippets/mvvmCross.snippet.
mvxpropdpfor the properties:
SetProperty(ref _property, value)method that comes from
MvxViewModelto simplify the implementation of the
mvxcmdfor the commands:
IMvxCommandis a build-in command interface to implement the
ICommandinterface, which can be binded to the UI controls to response the user behaviour, such as click event of the
Button, or select event of the
ICommondis mostly used in the
MVVMapplications to separate the tight coupling between the UI and the event handlers. Most of popular
MVVMframeworks in .NET provide an implementation of
ICommand, such as
ViewModellooks like this:
ViewModelto accept the input from the user and show the greeting message. We also have a command to respond the click event of a button. In the constructor method, there is a param called
greetingService. I will inject the implementation of the interface in the next section.