Click here to Skip to main content
15,867,704 members
Articles / Desktop Programming / WPF

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

Rate me:
Please Sign up or sign in to vote.
4.67/5 (8 votes)
29 May 2012CPOL6 min read 50.5K   3.1K   26   13
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.

Image 1


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.
Image 2

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.

Image 3

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.
      Image 4
    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.
      Image 5
    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.
      Image 6
    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:
      Image 7
  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.

Image 8

The DataContext links the current UI with our ContactViewModel.

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

Image 9

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)


Written By
CEO Addya Technologies
India India
"I am the CEO"
An Entrepreneur, Driving an Business Transformation Unit.

Comments and Discussions

 
BugApplicationViewStateChangedEventArgs error Pin
P1122-Aug-12 18:57
P1122-Aug-12 18:57 
Questionhow to handle a single instance of Model for mulitple views? Pin
fahad.sust14-Aug-12 22:53
fahad.sust14-Aug-12 22:53 
AnswerRe: how to handle a single instance of Model for mulitple views? Pin
Marco11122-Aug-12 17:19
Marco11122-Aug-12 17:19 
AnswerRe: how to handle a single instance of Model for mulitple views? Pin
P1122-Aug-12 18:52
P1122-Aug-12 18:52 
GeneralMy vote of 4 Pin
Farhan Ghumra28-Jun-12 0:27
professionalFarhan Ghumra28-Jun-12 0:27 
QuestionFile Access Pin
d853515@rtrtr.com11-Jun-12 8:45
d853515@rtrtr.com11-Jun-12 8:45 
AnswerRe: File Access Pin
Ninja__Turtle8-Dec-12 17:32
Ninja__Turtle8-Dec-12 17:32 
SuggestionTemplate and Images ! Pin
Vivek Krishnamurthy29-May-12 19:34
Vivek Krishnamurthy29-May-12 19:34 
Images seems to be of poor quality, can you please udpate them.

Also, It would be better if you can fit your article into code project article template.
Regards,
Vivek

GeneralMy vote of 5 Pin
P1129-May-12 7:24
P1129-May-12 7:24 
QuestionMy vote Pin
saj_2125-May-12 20:43
saj_2125-May-12 20:43 
GeneralMy vote of 5 Pin
saj_2125-May-12 20:42
saj_2125-May-12 20:42 
GeneralRe: My vote of 5 Pin
santosh_pathak25-May-12 20:44
santosh_pathak25-May-12 20:44 
GeneralRe: My vote of 5 Pin
Ninja__Turtle8-Dec-12 17:34
Ninja__Turtle8-Dec-12 17:34 

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

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