Friday, May 27, 2011

Silverlight / WPF MVVM - It is just a pattern

Hi,

lately there is a big hype around MVVM (Model-View-ViewModel), but most of the developers cant really understand it.

I have a personal opinion that is based in my experience and in my pragmatic way to see the things.
MVVM is just a pattern, and as a pattern it must be used according your challenge (most of people would use the word problem, but for me problem = challenge) and adapted to your needs.

In this post i wont tell you all the history and theory about it but you can check this articles:

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
http://blogs.msdn.com/b/johngossman/archive/2005/10/08/478683.aspx
http://en.wikipedia.org/wiki/Model_View_ViewModel

I will tell you how to implement the MVVM base for your application and to "glue" the View to your ViewModel using binding, all the source code is provided in the bottom of the article.

- ViewModelBase: this classe should be the base for all your ViewModels, wich mean all your ViewModels class should extend this one, and all the public properties of your ViewModelBase should call the OnNotifyPropertyChanged method when their value is set.

- RelayCommand: this one is also really important because is the base for all my command bindings, wich allow me to "bind code" to the control command, this means that in your ViewModelBase you will need to have a property of this type if you need to use commands in your view.

This is really the basic, but to start is more than enough and was where i felt more dificulties to understand what was MVVM really about. But you still need to "glue" it to the view, so here are some examples:

- Declare the namespace in you control:
   xmlns:ViewModel="clr-namespace:MyApp.ViewModel.Dialogs"

- Specify the data context of your control (in this case it is a child window):
   < controls:ChildWindow.DataContext>
        < ViewModel:LogonViewModel />
  
< /controls:ChildWindow.DataContext> 
 

- Bind properties:
   ItemsSource="{Binding Buttons}"

- Bind commands:

        Command="{Binding ActionCommand}"
 

Buttons specified in the example were added in the ViewModel:


new List{
new DialogButtonViewModelBase("Cancel", new RelayCommand(() =>
{
MessageBox.Show("Dont want to be logged in.");
})),
new DialogButtonViewModelBase("Ok", new RelayCommand(() =>
{
MessageBox.Show("Ok im logged in.");
})),
})





Source Code:

https://rapidshare.com/files/2608105881/Source.zip

References:

http://blog.galasoft.ch/Default.aspx
http://mvvmlight.codeplex.com/

2 comments:

  1. zip code files

    wow!!!!!beautiful blog but your post is very small.

    ReplyDelete
  2. Hi,

    I completely agree with you but that is the purpose of this blog, code snippets.

    Thank you for your feedback

    ReplyDelete