A few months ago I took the leap from WinForms programming to WPF and quite naturally, I took to it like a duck to water. Well, to be honest I had been developing Silverlight applications since its inception and being that Silverlight is a subset of WPF it required a low learning curve to catch on. However, the concept of Commanding was a bit different in WPF and I soon began to see how much more powerful Commanding in WPF was compared to Silverlight.
One of the areas in which Commanding is exemplary is in the way in which it complements MVVM. But what is MVVM, and why is it useful? This is the toughest concept (In my opinion) to grasp when it comes to WPF (and Silverlight) programming. Why you ask? Because it is simple and as developers we often like code or concepts that warp our minds, so when we figure it out we can brag to our peers how it only took 2 hours to understand and implement the next BIG thing (No I am not projecting). On a side not, I have found that everyone one who blogs about MVVM complicate it by adding too much code which just throws you for a loop. Simplicity is the key to all things complicated. So let’s delve into a little theory and we will finish up with some short-to-the-point code.
The purpose of this post is to
a. Give a simple and clear definition of Model View View-Model
b. Provide a clear and simple sample that clearly illustrates MVVM usage
Just in case you cannot read the text in the image here it is below:
- The View holds a reference to the ViewModel. The View basically displays stuff by Binding to entities in the View Model.
- The ViewModel exposes Commands, Notifiable Properties, and Observable Collections to the View. The View Binds to these ViewModel entities/members
- The Model is your data and or application objects that move data while applying Application Logic. If you have a Business Layer then you might not need this.
Above is a simple figure that tells you exactly what MVVM is. In my own words, the ViewModel is the most significant in the entire pattern as it is the glue that sits between the View and the Model and binds both of them together. Now let’s explore some code. Continue reading