Click here to Skip to main content
Click here to Skip to main content

An Address Book Application Made in MVVM For Metro Style App in Windows 8

, 29 May 2012
Rate this:
Please Sign up or sign in to vote.
Hands on developing MVVM Application without any Frameworks

Introduction

This article is a demo on developing MVVM Application Without any Frameworks.  

The new framework to hit WPF world is the MVVM framework. MVVM stands for Model - View - ViewModel. I will not explain the theory stuff here, for that you can refer this article. We will build this MVVM application WITHOUT using any frameworks. Just our own good'ol C# code.

In short,

  • Model - The basic unit of your application. It's nothing but simple class
  • ViewModel - The collection of "Model" like a List<> or ObservableCollection<>. It also contains code to hook-up the appropriate View events
  • View - This is the UI. You put your buttons, textblocks, textboxes and listboxes here

So lets get started. Fire-up Visual Studio 2011. Click on new Project. Select Metro and Blank Application. Hit Ok.


The first screen that you'll get is the default metro UI. Its nothing much than a blank black background. No buttons. Nothing. The code-behind contains few default lines of codes and a lot of comments. We will be using the code-behind only once, to write a single line of code in the constructor.

Now create 2 folders in the solution. Model and ViewModel. The Model folder will contain our "class" and ViewModel will contain, well, class but these classes will represent a collection of the Model's classes and will also contain code to wire the View with our ViewModel.

Next, we write our Model. For this application, I'll choose a simple Contact class having a Name and an Email and a GUID to identify it uniquely. So right click on Model folder, Add -> Class. Name the class as Contact.cs. Import the namespace System.ComponentModel, since we will be using the INotifyPropertyChanged interface. This will allow the ViewModel to communicate to the Model if something has changed. I'll keep the discussion simple.

After the Model, lets now focus on ViewModel. Right-click on the ViewModel folder, add -> class.
Since this ViewModel will work with our Contact.cs Model, we'll name it as "ContactViewModel.cs". Click Ok.

Now pay close attention, this is where the MVVM magic happens. Our ContactViewModel implements the INotifyPropertyChanged interface, this time to notify the changes in properties to the View and vice-versa. Import System.ComponentModel and implicitly implement INotifyPropertyChanged.
I'll make it simple here on how-to construct a basic ViewModel.

  1. Create a List<> property of the Model. Here I'll create an ObservableCollection<Contact> property called "Contacts" (see the plural form!) For this you will need to import System.Collections.ObjectModel and also import the Model reference by adding import Mvvm2_Basic.Model.
  2. Next, we need something to link up our ViewModel with the View. We will create a class which will invoke the proper methods when any event occurs on the View (say button click). This class will be a generic class and will be used for all the Button click events.
    1. Right-click the ViewModel folder and Add -> Class. Name the class as MyCommand OR you can create a new class in the existing file.
    2. This class implements a mechanism called as "callbacks" in which "we pass the *name* of a method to another method and tell the another method to called the named method when the another method finishes its work" It sounds crazy and confusing, but its really easy to understand. Study few examples of callbacks and you will find it rather easy.
    3. For simplicity, I will create MyCommand in the same class. MyCommand will implement the ICommand interface. For that you will need to import System.Windows.Input namespace.
    4. After setting the command, lets now make use of it. To do that, we will create appropriate methods to handle the different events generated by our UI.
      The events that we are interested in are Add, Save, Update, Delete and Refresh. These events will be generated by clicking of the respective buttons on the View.
    5. The methods take an object parameter. We will create 5 methods.
    6. Now after our methods are ready, lets hook them up with the buttons on the View. To do that, we will create 5 properties of MyCommand class to represent our 5 methods. These 5 properties will then be hooked-up to the 5 buttons on our View. So now you must have got the idea that we do not directly link our methods to the UI (as in code-behind traditional approach).
    7. So one end of these 5 properties will be linked to our 5 methods and the other end will be linked to the buttons. If you have a closer look at our MyCommand class, you will see that in the constructor we are accepting a callback "Action<T>" parameter. This parameter contains the reference to one of the 5 methods. To keep it simple, the constructor in MyCommand class will hook-up our MyCommand Property to one of the 5 methods.
    8. Now in the constructor of "ContactViewModel" we will define these properties. While doing that, we pass the name of the method that we need to link with the property. This is important since we need to make sure that when we click "Save" button then only the method performing "save" operation will be called. This is done as follows:
  3. That's it. We've done with our ViewModel for now. Next step would be to create the View.

Our View is a very simple UI. As mentioned earlier, we only have 5 buttons on our View. So lets go ahead and create our View. For our View, we will use the BlankPage.xaml. Open BlankPage.xaml.cs (the code-behind). We need to tell our View that whatever events will be raised on the view, they will be handled by our ViewModel.

The DataContext links the current UI with our ContactViewModel.

Now lets create our 5 buttons. They will be "Refresh", "Add New", "Save", "Update", "Delete"

Note the "Command" property on every button. The command property tells the View where to look for, when that button is clicked. In our Command property, we specify the ViewModel property that we want to invoke. That ViewModel property will then invoke the appropriate method.

You should've understood by now that its the head-ache of the ViewModel property to invoke the appropriate method. This separates the concern of the UI about reacting to events. This entire setup allows us to test each "part" separately. 

So when "Save" button is clicked, SaveCommand property is invoked. The SaveCommand property from ViewModel has the signature of OnSave() method passed in it. Hence ViewModel's SaveCommand will finally call the OnSave() method.

You can see in the output window when each method is called, it outputs some text that we've written in Debug.WriteLine in every method. 

Very well. This completes the basic skeleton for our MVVM XML Metro application. In the next series, we will see how to perform CRUD operations using XML file. Till then stay tuned. 

If Images in this article isnt proper then please Download the images

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

santosh_pathak
CEO Addya Technologies
India India
"I am the CEO"
An Entrepreneur, Driving an Business Transformation Unit.
Follow on   Twitter

Comments and Discussions

 
BugApplicationViewStateChangedEventArgs error PinmemberP1122-Aug-12 18:57 
Questionhow to handle a single instance of Model for mulitple views? Pinmemberfahad.sust14-Aug-12 22:53 
AnswerRe: how to handle a single instance of Model for mulitple views? PinmemberMarco11122-Aug-12 17:19 
AnswerRe: how to handle a single instance of Model for mulitple views? PinmemberP1122-Aug-12 18:52 
GeneralMy vote of 4 PinmemberFarhan Ghumra28-Jun-12 0:27 
QuestionFile Access Pinmemberd853515@rtrtr.com11-Jun-12 8:45 
AnswerRe: File Access PinmemberNinja__Turtle8-Dec-12 17:32 
SuggestionTemplate and Images ! PinmemberVivek Krishnamurthy29-May-12 19:34 
GeneralMy vote of 5 PinmemberP1129-May-12 7:24 
QuestionMy vote Pinmembersaj_2125-May-12 20:43 
GeneralMy vote of 5 Pinmembersaj_2125-May-12 20:42 
GeneralRe: My vote of 5 Pinmembersantosh_pathak25-May-12 20:44 
GeneralRe: My vote of 5 PinmemberNinja__Turtle8-Dec-12 17:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140902.1 | Last Updated 30 May 2012
Article Copyright 2012 by santosh_pathak
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid