Universal Windows Platform With MVVM

Introduction

MVVM” stands for “Model-View-ViewModel”. Model basically initialize properties, attributes whatever you say, and “ViewModel” contains all data of your application. Finally, View represents actual representation of data in your screen. Basically Data Binding works between “ViewModel” and “View “layer, “View” requests command and “ViewModel” accept it and responses to the “View”. I’m not going to the complete theoretical knowledge. I will try to give you the basic idea what “MVVM” is.

Now, let’s get crack in the best practice in this super awesome architectural model.

Creating a New Project

Firstly, open up a new project and name it “MVVMEx” or whatever you want. Now, add three folders “Models”, “ViewModels” and “Views” one by one, like this.

Add new folder
                                                         Figure 1

It should look exactly like the following figure 2.

Solution Explorer
                                       Figure 2

Adding a New Page

Now, in “Views” folder right click and add a new “Blank Page”, give it a name “AutoView”.

Blank APP
                                                                        Figure 3

Changing the Starting Page

Now one more thing we’ve to do, is changing our starting page. For that, you’ve to go “app.xaml.cs” and change this line of code,

  1. if (rootFrame.Content == null)  
  2. {  
  3.     // When the navigation stack isn't restored navigate to the first page,  
  4.     // configuring the new page by passing required information as a navigation  
  5.     // parameter  
  6.     rootFrame.Navigate(typeof(Views.AutoView), e.Arguments);  
  7. }  
Listing 1

Because, we’ve replaced our “MainPage.xaml” and added a new page “AutoView.xaml”.

Adding Classes

Now, similarly right click on the “Model” folder and add a new class named “Auto.cs”. Again right click on the “ViewModels” folder and add another class named “AutoViewModel.cs”. After setup, your Solution Explorer will look like the following figure 4.

ViewModels
                                    Figure 4

Now we’ll modify our “AutoView.xaml” as follows.

Modifying “AutoView.xaml” Page

Setting up app title and information.
  1. <!-- Title Panel -->  
  2. <StackPanel Grid.Row="0" Margin="19,0,0,0">  
  3.     <TextBlock Text="Learn With BD Devs" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>  
  4.     <TextBlock Text="MVVM" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>  
  5. </StackPanel>  
Listing 2

Modifying main grid
  1. <!--TODO: Content should be placed within the following grid-->  
  2. <Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0">  
  3.     <TextBlock Height="50"  
  4.                HorizontalAlignment="Left"  
  5.                Margin="10,10,0,0"  
  6.                Name="manufacturerBlock"  
  7.                Text="{Binding manufacturer,Mode=OneWay}"  
  8.                VerticalAlignment="Top"   
  9.                Width="342" FontSize="24"/>  
  10.     <TextBlock Height="50"   
  11.                HorizontalAlignment="Left"  
  12.                Margin="10,65,0,0"  
  13.                Name="modelBlock"  
  14.                Text="{Binding model,Mode=OneWay}"  
  15.                VerticalAlignment="Top"  
  16.                Width="342" FontSize="24"/>  
  17.     <TextBlock Height="50"  
  18.                HorizontalAlignment="Left"  
  19.                Margin="10,120,0,0"  
  20.                Name="colorBlock"  
  21.                Text="{Binding color,Mode=OneWay}"  
  22.                VerticalAlignment="Top"  
  23.                Width="342" FontSize="24"/>  
  24.     <TextBlock Height="50"  
  25.                HorizontalAlignment="Left"  
  26.              Margin="10,175,0,0"  
  27.                x:Name="yearBlock"  
  28.                Text="{Binding year, Mode=OneWay}"  
  29.                VerticalAlignment="Top"  
  30.                Width="342" FontSize="24"/>    
  31. </Grid>  
Listing 3

Implementation of “BaseModel.cs” Class

Now, we’ll move to our “Models” folder and initialize auto’s properties, but before that, we’ve to add another class name “BaseModel.cs” in our “Common” folder.
  1. public class BaseModel : INotifyPropertyChanged  
  2. {  
  3.     public event PropertyChangedEventHandler PropertyChanged;  
  4.   
  5.     protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)  
  6.     {  
  7.         if (object.Equals(storage, value)) return false;  
  8.         storage = value;  
  9.         this.OnPropertyChaned(propertyName);  
  10.         return true;  
  11.     }  
  12.   
  13.     private void OnPropertyChaned(string propertyName)  
  14.     {  
  15.         var eventHandler = this.PropertyChanged;  
  16.         if (eventHandler != null)  
  17.             eventHandler(thisnew PropertyChangedEventArgs(propertyName));  
  18.     }  
  19. }  
Listing 4

It’s our “INotifyPropertyChanged” interface. As, we’ve said in best practice, you’ve make your code as much clean as you can.

Implementation of “Auto.cs” Class

Now, move back to our “Auto.cs” class. The initialized properties are given below:
  1. public class Auto : BaseModel  
  2. {  
  3.     private string _manufacturer;  
  4.     private string _model;  
  5.     private string _color;  
  6.     private int _year;  
  7.   
  8.     public string manufacturer  
  9.     {  
  10.         get { return _manufacturer; }  
  11.   
  12.         set { this.SetProperty(ref this._manufacturer, value); }  
  13.     }  
  14.   
  15.     public string model  
  16.     {  
  17.         get { return _model; }  
  18.   
  19.         set { this.SetProperty(ref this._model, value); }  
  20.     }  
  21.   
  22.     public string color  
  23.     {  
  24.         get { return _color; }  
  25.   
  26.         set { this.SetProperty(ref this._color, value); }  
  27.     }  
  28.   
  29.     public int year  
  30.     {  
  31.         get { return _year; }  
  32.   
  33.         set { this.SetProperty(ref this._year, value); }  
  34.     }  
  35. }  
Listing 5

Here, we’ve inherited all the public properties of “BaseModel.cs” class, and fire the value of data in setter. Just simple logic of OOP (Object Oriented Programming).

Setting Up Data in “AutoViewModel.cs” Class

Now, we’ll set the data of our “Auto” properties in “AutoViewModel.cs” class.
  1. public class AutoViewModel : Auto  
  2. {  
  3.     Auto _auto = new Auto  
  4.     {  
  5.         manufacturer = "Oldsmobile",  
  6.         model = "Cutlas Supreme",  
  7.         color = "Silver",  
  8.         year = 1988  
  9.     };  
  10.   
  11.     public AutoViewModel()  
  12.     {  
  13.         this.manufacturer = _auto.manufacturer;  
  14.         this.model = _auto.model;  
  15.         this.color = _auto.color;  
  16.         this.year = _auto.year;  
  17.     }  
  18. }  
Listing 6

Here, we’ve used Inheritance and inherited “Auto.cs” class like before, so that we can access all the public properties of “Auto.cs” class.

We created a “_auto” object of “Auto.cs” class and initialized all the values here, and in constructor “AutoViewModel” we make references of these properties.

Setting Up DataContext in “AutoView.xaml.cs” Class

It’s almost done. Now, to visualize the data of our “AutoViewModel.cs” class, we have to instantiate in our “AutoView.xaml.cs” class. To do so, change these line of code as follows.
  1. private AutoViewModel defaultViewModel = new AutoViewModel();  
  2.    
  3. public AutoView()  
  4. {  
  5.     this.InitializeComponent();  
  6. ...  
  7.     this.DataContext = defaultViewModel;  
  8. }  
  9.    
  10. public AutoViewModel DefaultViewModel  
  11. {  
  12.     get { return this.defaultViewModel; }  
  13. }  
Listing 7

Here, we’ve created a “defaultViewModel” object of “AutoViewModel.cs” class and make it the “DataContext” of our “AutoView.xaml.cs” class in constructor. It actually retrieves all data from “AutoViewModel” constructor and shows in “ContentRoot” grid of “AutoView.xaml”.

Running the Application

Now, it’s time to build our project. After you run the application, it should look exactly like the following screenshot.

MVVM
                                             Figure 5


Summary

So, that’s it. Hope you’ve understood the concept of “MVVM” and how to implement in your project. It’s really helpful when you’ll work in big project and you’ve to handle large amount of data.
Happy coding!

You can download the full source code, here.

 

Up Next
    Ebook Download
    View all
    Learn
    View all