Design Patterns: In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn't a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.
What is MVVM?
It’s an architectural pattern created by John Gossman from WPF team.
MVVM is Model-View-ViewModel Design pattern .But this is different from Common Design pattern which is created by GOF (Gang Of Four) The four authors were Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides.
Model => Holds the Data.
View => Presents/Shows the Data.
ViewModel =>Holds the Models which is Presented/Showed in a View.
When we are building WPF or Silverlight applications is better to use MVVM pattern because this pattern offers the following benefits.
- Testability ( ViewModel is easier to unit test than code-behind or event driven code)
- Clear separation between UX designer and developer
- Increases the "Blend ability" of your view
- Model never needs to be changed to support changes to the view
- ViewModel rarely needs to be changed to support changes to the view
- No duplicated code to update views
The Important is MVVM makes uses of Silverlight & WPF Binding.
Here I am going to show how to use MVVM pattern when building Silverlight application. Here i am not going to use any framework tooling. Here is the workflow I am going to follow.
- Create a Silverlight Application.
- Create Model, View,ViewModel Folders.
- Add or Create a Model class with some properties . Here I am going to create Custom class. ( we can use EF , WCF etc..).
- Implements INotifyPropertyChanged Interface.
- Create ViewModelBase and ViewModel Classes.
- Create a View.
- Do the Binding.
First Fire up VS.NET 2010 and Create a Silverlight Application Project.
Once project is created now we need to add the following Model , View , ViewModel folders as shown below.
Now we need to create Model. To do that right click on Model Folder and Add the class called UserProfile and add the following public properties as shown below.
Now right click on ViewModel folder and add the following classes.
This viewModelbase class just implements the INotifyPropertyChanged Interface this way both source and Target objects are in Sync.
The ObservableCollection class automatically implements INotifyPropertyChanged Interface.
Now right click on View Folder and add the Silverlight Usercontrol name it as UserProfileView.XAML And add the following XAML code
And add the following code in the UserProfileView.XAML code behind.
Here i am creating 100 user profiles and adding to ObervableCollection and setting to UserProfileViewModel class and setting Datacontext.
I hope i explained MVVM pattern very simple and everyone can understand easily . Here i used Properties binding even we can use ICommand as well (Silverlight 4.0). I am happy to answer this blog readers questions.