Chapter 3. MVVM Design Pattern

The previous chapter described the initial steps of developing the Windows Phone 8 game, including creating the project and designing the first screen using the XAML language. You learned how to use controls, styles, resources, data binding, as well as localization features. All of these functionalities were used to create the Menu screen, which you can see in the emulator or on the phone while running your game.

In this chapter, you will prepare preliminary versions of all the remaining screens. This will allow you to get to know the MVVM design pattern, data templates, and other mechanisms useful for developing applications for the Windows Phone 8 platform. So, let's continue working on your first game!

Model-View-ViewModel

The first application page in the managed area of your game consists of two files, .xaml with XAML code regarding the user interface and .xaml.cs (code-behind) with C# code that can be used to interact with the user interface as well as perform any additional operations (for example, getting data from external sources). Thus, in these two files, you can create the user interface and place all logic related to a particular page.

Such a solution can be acceptable for simple projects, but in more complex projects, it can lead to several problems, for example, with maintenance and making further modifications. The situation can be even more complicated, if the project is being created by a team where developers and designers are working together. Let's just think about a scenario when you need to replace the mechanism of getting and updating ranks data, including their source and format. If the whole logic is placed in multiple .xaml.cs files, then you need to modify all of them, ensure that changes do not have an impact on the user interface code, as well as test the new version, which can be quite complicated because the logic is strictly connected with the user interface. Thus, separating various project parts is really important and can be beneficial for the overall project quality.

The process of developing applications for Windows Phone 8 platform can be significantly improved by using the Model-View-ViewModel (MVVM) design pattern. This approach splits the project into three parts (view, view model, and model), as presented in the following figure (based on http://msdn.microsoft.com/library/hh821028):

Model-View-ViewModel

The view part is strictly related to how the application is presented to the user. It contains the XAML code describing pages and controls as well as binds data from the view model. This part also indicates commands from the view model that are executed after performing some operations in the user interface (for example, clicking a button).

The model (also referred as the data model) represents the business logic, thus, it can contain, for example, classes responsible for making calculations as well as performing operations using the database and web services. This part can define some additional classes that represent various elements from the project domain such as a single rank item.

The view model gets and updates data from the model, as well as provides this data to the view in a suitable format. As you can see, the view model acts as a central place between the view and the model.

Such a design pattern has several advantages. First of all, it separates various parts of the project, especially the user interface and logic. Therefore, they are easier to modify and maintain. The MVVM can improve teamwork, because developers and designers can focus on particular areas and know where a given project part should be located. Regarding the project quality, using this design pattern can have a beneficial impact on the code and make unit testing significantly easier due to independency of the model and view model from the user interface.

The MVVM pattern is consistent with the concept of the Windows Phone 8 applications, thus, it is a good idea to use it in your projects. It is worth mentioning that there are some possible implementations, including creating your own solution or using existing libraries. To keep things simple, at the beginning of the adventure with Windows Phone 8 programming, you will create a simple implementation of MVVM.

Note

MVVM is not the only design pattern that aims to separate various parts of the project and improve its design. Among other possibilities, MVC (Model-View-Controller) and MVP (Model-View-Presenter) exist. They have various applications and differ from the MVVM design pattern, which is implemented in the following part of this chapter.

Simple implementation

The simple approach of MVVM implementation splits the project into three parts, which are placed in directories:

  • Views - For the user interface (.xaml and .xaml.cs files)
  • ViewModels - With classes representing view models for the screens
  • Models - Containing the domain model and additional business logic

The view model for each screen (for example, the Map screen) is implemented as a class deriving from the abstract ViewModel class, placed in the ViewModels directory:

public abstract class ViewModel : INotifyPropertyChanged
{
  public NavigationService NavigationService { get; set; }
  public event PropertyChangedEventHandler PropertyChanged;
  protected void OnPropertyChanged(string name)
  {
    if (this.PropertyChanged != null)
    {
      this.PropertyChanged(this,
        new PropertyChangedEventArgs(name));
    }
  }
}

Tip

To create a class, you should select the Add and New Item options from the context menu of the project and choose the Class element. Another possibility is to click on the Add and Class options directly from the context menu. In both cases, you need to specify a class name and then click on the Add button.

As you can see in the previous code, the ViewModel class implements the INotifyPropertyChanged interface (from the System.ComponentModel namespace), which makes it possible to track changes in the values of the properties. Such a feature is important for data binding because you need to update the user interface as soon as the values of the properties from the view model class are modified. The INotifyPropertyChanged interface requires the PropertyChanged event, which should be triggered whenever a property value is changed. To simplify this operation, you create the OnPropertyChanged method, which takes the name of the property (whose value has been modified) as a parameter.

The abstract class also contains the NavigationService property, which allows you to navigate to another screen directly from the view model. A type of this property is NavigationService from the System.Windows.Navigation namespace.

Apart from the ViewModel class, you need to create the Command class, also inside the ViewModels directory. It represents a single command that is executed when the user performs some operation in the user interface, for example, clicking on a button. Such a class implements the ICommand interface from the System.Windows.Input namespace as follows:

public class Command : ICommand
{
  private Action m_action;
  public Command(Action action) { this.m_action = action; }
  public void Execute(object parameter) { this.m_action(); }
  public event EventHandler CanExecuteChanged;
  public bool CanExecute(object parameter) { return true; }
}

By implementing the ICommand interface, the class will have the Execute and CanExecute methods, as well as the CanExecuteChanged event. However, you can assume that the command can be always executed, thus the CanExecute method always returns the TRUE value. Regarding the Execute method, you call the method specified in the m_action field. You set it in the constructor, by passing the Action delegate as the parameter. Such a delegate represents a method, which does not return any value and has no parameters.

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

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