Working with events and commands
It's time to update our code to move the event handling code to MainViewModel
. By the end of this section, you will have removed all the code that was added to the MainPage.xaml.cs
file, except for the ViewModel
property. This will be great for separation of concerns, as well as for the maintainability and testability of the project.
We could simply use the same method of hooking up events with the Add button's Click
event and connect it to a method on the MainViewModel
class. There are two problems with this approach, detailed here:
- The View and View Model layers become more tightly coupled, reducing maintainability.
- UI concerns are injected into the view model, reducing the testability of the class.
Let's take another route to tackle it. The MVVM pattern has the concept of Commands to handle events. Instead of adding a handler to the event of our view element, we will bind that event to a property on the view model...