This post accompanies my Getting Started with MVVM Visual Studio Toolbox episode. In that episode, In that episode, I showed how to get started with MVVM in XAML apps. I showed a simple Windows Store app calls a WCF service that manages customers and projects data in a SQL Server database. The base version of the app uses no MVVM. I then showed five iterations of the app, each adding a piece of MVVM. The sample code for this includes all six projects.
Issue: Code behind makes it difficult to test. How do you test data code? You have to run the app. It would be nice to break out the data into a separate unit of work. We want a separation between the views and the code that works with the data.
In this lesson, we create a ViewModel for each View. Each ViewModel has a property that represents the data on the corresponding page, so you can just bind to the ViewModel.
All the data access code has been moved into the ViewModels so you could unit test the data methods without having to run the app or finish the UI.
Move all data access code into ViewModels.
LoadState and button clicks no longer have data code. They call methods in the VMs that have the data code.
This is the bare minimum to be MVVM.
Issue: ViewModels talk directly to WCF service. What happens if you want to swap the data source? Perhaps you want to use an Azure Mobile Service, or Web API, or a service that returns JSON. Or perhaps you decide to stop calling a service and switch to entirely local data.
Issue: Our model has classes for Customer and Project, but they are contained in the service proxy code. If the data model is simple enough, and it is in this example, that is not a problem. However,
In this lesson, we will remove the data access code from the ViewModels. We will create a service layer that talks to the WCF service. The ViewModel calls the service layer. That way, if we want to change the method of data access, we only have to change code in the service layer. This also gives us the ability to unit test the data calls.
Use Commands instead of Button Click handlers.
We can use RelayCommand class in Common folder rather to wire up commands.
Bind SelectedItem of GridView to SelectedCustomer/SelectedProject properties of ViewModels
Ideally, we would use a Command here. There is code out there to wire up the ItemClicked to a Command, but how do you know what customer/project was clicked?
Call a public method of the ViewModel and pass e.ClickedItem as an argument. Admittedly a hack.
The RelayCommand in the Common folder does not enable us to pass parameters to it. We need a generic RelayCommand. Then we need code that will wire up ItemClick to that generic RelayCommand.