When building any application, it is always a good practice to follow tried and tested design-patterns which will help in separation of concerns, code-reuse, maintainability, testability etc.… Just like ASP.NET there is MVC, for XAML based technologies (like Silverlight, Windows Presentation Foundation, Windows Store and Windows Phone apps), there is MVVM.
In this case, MVVM stands for – Model View ViewModel. As name suggests Model is nothing but classes representing data/entities. View represent actual view (pages in this context) whereas ViewModel does the binding between View and Model.
There are many frameworks out there which helps to build Windows Phone apps using MVVM pattern like Prism from Microsoft and MVVM Light from GalaSoft. In this blog, we’ll focus about MVVM Light.
First create a Windows Phone application.
Select Windows Phone 8.0 as OS Version in next dialog box.
Now, click on TOOLS > Library Package Manager > Manage NuGet Packages for Solution and search for MVVM Light in Online Gallery and install the same
When MVVM Light toolkit is installed, it modified App.Xaml file to instantiate the ViewModelLocator. These ViewModels are added in ViewModel folder.
MainViewModel is responsible to communicate between view and model. However, to keep things simple, we’ll expose a ApplicationName property which we’ll bind to Page.
Now, to bind ViewModel to View, in MainPage.xaml, add following code in phone:ApplicationPage element:
Now, bind ApplicationName to the textblock which displays App Name in MainPage.xaml
As soon as you modify above code, the UI changes and shows the Application Name. This is the beauty of using MVVM.
In next few blog-posts we’ll explore more about patterns and best practices in Windows Phone applications. Stay tuned!