Getting Started with Visual Studio 2013, Windows Phone 8.1, Window Store 8.1, MVVM –Part 1 of N

With the recent release of Universal Apps, Windows Phone 8.1, Visual Studio 2013 Ultimate Update 2 RC , Windows Store 8.1 Update & Windows 8.1 update from Microsoft, I thought to blog some articles on these new technologies and there is no better design pattern to use than MVVM. So I will walk through some of the latest programming updates from MS along with MVVM.

Required Software’s:

Benefits of MVVM:

1. Separation of Concerns (View, ViewModel, Model)
2. Clean testable and manageable code. Can include presentation tier logic in unit testing.
3. No code behind code, so the presentation layer and the logic is loosely coupled.
4. Better way of data binding.
5. With the new Window Runtime support for Windows Phone 8.1, we can now use the same Windows Store code for ICommand pattern implementation.

Overview MVVM Layers

image

Steps to Implement MVVM:

Lets get our hands dirty. Here we are going to develop a Windows Phone 8.1 application using Windows Runtime & XAML (Not Silverlight). Figure 1 shows the UI we are planning to develop.

Before writing code, analyze what we want to achieve and then come up with the class names, draw relation ships on paper and see how all the components fit together. Here I have two variables firstname and lastname and I wanted to show the data in the UI as shown in figure 1. So lets use MVVM to achieve this.

image

Figure 1: Views showing Model data using MVVM design pattern

Step 1: Fun with MVVM begins. Create a Universal Project by opening VS 2013 –> New –> Project –> Templates->Visual C#->Store Apps->Universal Apps and select Blank App (Universal Apps). Name it as UniBlank_MVVMBasics as shown in Figure 2.

image

Figure 2: New Universal Apps Project template in Visual Studio 2013

Step 2: VS 2013 creates two projects. One for Windows Store and other for Windows Phone. Both use Windows Runtime API as the core targeting 8.1 platforms. Shared project is the shared component between the two projects and we will get to this when we learn more about Universal Apps Project template.

image

Figure 3: Universal Apps Projects in VS 2013.

Step 3: Adding a class. Right click on UniBlank_MVVMBasics.WindowsPhone –>Add->Class as shown in Figure 4.image

Figure 4: Adding a class in Visual Studio 2013.

Step 5: Name it as Person.cs as shown in Figure 5.image

Figure 5: Add New Item Dialog

Step 6: Create a Simple Model (Person.cs) with required properties and implement PropertyChanged property of INotifyPropertyChanged.

Person Class Code
  1. class Person : INotifyPropertyChanged
  2.     {
  3.         public event PropertyChangedEventHandler PropertyChanged;
  4.  
  5.         private string _firstName;
  6.         public string FirstName
  7.         {
  8.             get
  9.             {
  10.                 return _firstName;
  11.             }
  12.  
  13.             set
  14.             {
  15.                 if (_firstName != value)
  16.                 {
  17.                     _firstName = value;
  18.                     OnPropertyChanged("FirstName");
  19.                 }
  20.             }
  21.         }
  22.  
  23.         private string _lastName;
  24.         public string LastName
  25.         {
  26.             get
  27.             {
  28.                 return _lastName;
  29.             }
  30.  
  31.             set
  32.             {
  33.                 if (_lastName != value)
  34.                 {
  35.                     _lastName = value;
  36.                     OnPropertyChanged("LastName");
  37.                 }
  38.             }
  39.  
  40.         }
  41.  
  42.         public void OnPropertyChanged(string property)
  43.         {
  44.             if (PropertyChanged != null)
  45.             {
  46.                 PropertyChanged(this, new PropertyChangedEventArgs(property));
  47.             }
  48.         }
  49.     }

Step 7: Create a ViewModel (PersonViewModel.cs) with required logic to bind Model to ViewModel. (Repeat step 3 t step 5 and name class as PersonViewModel.cs.

Code Snippet
  1. class PersonViewModel
  2.     {
  3.         public ObservableCollection<Person> Persons
  4.         {
  5.             get;
  6.             set;
  7.         }
  8.  
  9.         public void LoadPersons()
  10.         {
  11.             ObservableCollection<Person> _persons = new ObservableCollection<Person>();
  12.             _persons.Add(new Person{ FirstName="Bill", LastName="Gates"});
  13.             _persons.Add(new Person{ FirstName="Satya", LastName="Nadella"});
  14.             Persons = _persons;
  15.         }
  16.     }

Step 8: Instead of using MainPage.XAML to show the data, let us create Views as we do typically in a software development. Create a View (PersonView.xaml) and bind the data with ViewModel. Add a User Control to the solution and name it as PersonView.xaml as shown in Figure 6.image

Figure 6: Adding View (User Control) to the project in VS 2013

Step 9: As we have to display firstname and lastname, lets use TextBlock’s. We will use  ItemsControl and Persons (observablecollection property) as DataContext and put them inside a DataTemplate to display the data from model in the view. In PersonView.XAML, write the following code inside Grid tag as shown below.

XAML code- Person User Control
  1. <Grid>
  2.         <StackPanel HorizontalAlignment="Left">
  3.             <ItemsControl ItemsSource="{Binding Path=Persons}">
  4.                 <ItemsControl.ItemTemplate>
  5.                     <DataTemplate>
  6.                         <StackPanel Orientation="Horizontal" Margin="20,20,0,0">
  7.                             <TextBlock Margin="10,0,20,0" Text="{Binding Path=FirstName, Mode=TwoWay}" Style="{StaticResource HeaderTextBlockStyle}"></TextBlock>
  8.                             <TextBlock Text="{Binding Path=LastName, Mode=TwoWay}" Style="{StaticResource HeaderTextBlockStyle}"></TextBlock>
  9.                         </StackPanel>
  10.                     </DataTemplate>
  11.                 </ItemsControl.ItemTemplate>
  12.             </ItemsControl>
  13.         </StackPanel>
  14.  
  15.     </Grid>

Step 10: In PersonView.xaml.cs, let us create an object of PersonViewModel class and pass it as DataContext to the View we just created as shown below.

PersonView.xaml.cs code
  1. private void UserControl_Loaded(object sender, RoutedEventArgs e)
  2. {
  3.     PersonViewModel personViewModelObject = new PersonViewModel();
  4.     personViewModelObject.LoadPersons();
  5.     this.DataContext = personViewModelObject;
  6. }

Step 11: In MainPage.xaml, let us import the xmlns:views=”using:UniBlank_MVVMBasics” namespace and put the views inside the grid as shown below.

MainPage.xaml code
  1. <Page
  2.     x:Class="UniBlank_MVVMBasics.MainPage"
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  5.     xmlns:local="using:UniBlank_MVVMBasics"
  6.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;
  7.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
  8.     mc:Ignorable="d"
  9.     Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
  10.     xmlns:views="using:UniBlank_MVVMBasics" >
  11.  
  12.     <Grid>
  13.         <views:PersonView></views:PersonView>
  14.     </Grid>
  15. </Page>

That’s it. Download the source code here.

Below are some of the points to remember about MVVM layers.

Model:

1. Represents the Data.
2. The Entity.
3. Model classes are non-visual classes that encapsulate the application’s data and business logic.
4. They are responsible for managing the application’s data and for ensuring its consistency and validity by encapsulating the required business rules and data validation logic.
5. The model classes do not directly reference the view or view model classes and have no dependency on how they are implemented.
6 The model classes typically provide property and collection change notification events through the INotifyPropertyChanged and INotifyCollectionChanged interfaces.
7. This allows them to be easily data bound in the view.
8. Model classes that represent collections of objects typically derive from the ObservableCollection<T> class.
9. The model classes typically provide data validation and error reporting through either the IDataErrorInfo or INotifyDataErrorInfo interfaces.
10. The model classes are typically used in conjunction with a service or repository that encapsulates data access and caching.
11. Not required to know where it gets its data from i.e from a WCF service. WCF RIA Services, etc.
12. May contain validation.

View:

1. The view is a visual element, such as a window, page, user control, or data template.
2. The view defines the controls contained in the view and their look and feel, visual layout and styling.
3. The view references the view model through its DataContext property.
4. The controls in the view are data bound to the properties and commands exposed by the ViewModel.
5. The view may customize the data binding behavior between the view and the view model.
For e.g, the view may use value converters to format the data to be displayed in the UI, or it may use validation rules to provide additional input data validation to the user.
6. The view defines and handles UI visual behavior, such as animations or transitions that may be triggered from a state change in the view model or via the user’s interaction with the UI.
7. The view’s code-behind may define UI logic to implement visual behavior that is difficult to express in XAML or that requires direct references to the specific UI controls defined in the view. 

ViewModel:

1. The ViewModel is a non-visual class and does not derive from any WPF or Silverlight base class.
2. It encapsulates the presentation logic required to support a use case or user task in the application.
3. The ViewModel is testable independently of the view and the model.
4. The ViewModel typically does not directly reference the view. It will have UI Friendly Entities, UI State, Actions and Public properties that are bound to a View.
5. It implements properties and commands to which the view can data bind.
6. It notifies the view of any state changes via change notification events via the INotifyPropertyChanged and INotifyCollectionChanged interfaces.
7. Interacts with View with various Commands.
8. The view model coordinates the view’s interaction with the model.
9. It may convert or manipulate data so that it can be easily consumed by the view and may implement additional properties that may not be present on the model.
10. It may also implement data validation via the IDataErrorInfo or INotifyDataErrorInfo interfaces.
11. The view model may define logical states that the view can represent visually to the user.
12. Invokes services to communicate outside the MVVM triad.

1 thought on “Getting Started with Visual Studio 2013, Windows Phone 8.1, Window Store 8.1, MVVM –Part 1 of N

  1. Pingback: Getting Started with Visual Studio 2013, Windows Phone 8.1, Window Store 8.1, MVVM –Part 2 of N | Software Architect, Technology Evangelist, Technology Consultant

Leave a comment