My MVVM in Silverlight notes
If you are new to WPF/Silverlight or have been living on Mars, Model-View-View Model is the undisputed winner in the WPF framework wars. If you are WPF only, you are off and running but if you are Silverlight, you need to do a little homework and decide if you want to cheat a bit from being a purest and call into the ViewModel from the View or stay true and use a helper class to provide the missing ICommand interface.
I liked to putter around with various frameworks for Flex like Cairngorm, MVC (and one without the Controller!), Mate which I really liked. I question why MVVM has not been attempted by the Flex community as its very declarative language friendly (XAML, MXML) and increases your ability to Unit Test.
So I spent a beautiful weekend afternoon investigating how best to join the mob and MVVM my future Silverlight apps and found the following links. Perhaps it will save others some time.
The problem is that Silverlight does not offer an implementation of the ICommand interface like WPF does.
Here, Maurice calls into the ViewModel from the UI code behind as in:
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
var viewModel = (CustomerViewModel)DataContext;
viewModel.Save();
}
This is a compromise in that (as Wes Aday says) “…the holy grail of MVVM is to make the UI code-behind a desolate wasteland. All the code is in the Viewmodel and loose coupling is achieved by using Data Binding (and its INotifyPropertyChanged) to keep the client updated with the latest data and Commanding which is the mechanism that lets the ViewModel be notifed when something interesting happens in the UI.”
Nikhil Kothari in “ViewModel Pattern in Silverlight using Behaviors” (which provides the equivalent of commands) uses Action Behaviors his mini-behavior framework to do the commanding
Shawn Wildermuth has written an article where he takes the same route the first cited above, namely he calls the ViewModel methods from within the UI code-behind
Josh Smith does a video and he calls into the viewModel too. But, here he creates an implementation of ICommand for Silverlight.
Wes Aday applies Josh’s solution in an easy to understand example here
Julian Dominguez makes ICommand happen in Silverlight via attached behaviors here.
Radenko Zec implements the MVVM pattern in Silverlight using SLEextensions – this is another Attached Behavior method (which Radenko says its the easiest) like Kothari’s.
Craig Shoemaker has a great rundown as well.
Finally, here’s a video explaining Shawns GameCatalog MVVM example.
Well, that should keep you busy… just wait for a rainy day. – Cheers!
[...] a recent post I wondered why MVVM, which is so popular in WPF (and now Silverlight as well), did not seem to be [...]