Background
Few days back I demonstrated a basic MVVM application using Silverlight 4. In the last post I refactored the same example to be even more MVVM friendly by using the concept of dependency injection. In this post I am going to demonstrate how to use MVVMLight toolkit to refactor the previous example. We’ll mainly be concentrating on making use of RealyCommand available in MVVMLight as a replacement for DelegateCommand and also having a code-behind fiel without any “code”. The wiring up of view and view model would be done through XAML using MVVM Light’s approach of using a ViewModelLocator service.
Integrate MVVMLight toolkit
First of all we need to to download the MVVMLight toolkit. These are multiple choices to integrate it with the solution. We could get it directly from the GalaSoft site and add the required dlls to our solution. Alternately we could use the latest approach of using something which is available out of the box in Visual Studio 2010 in the form of NuGet package. I’ll use this approach but if you prefer to handcraft things and have much more control over the location of dlls etc then you can follow the instructions on the codeplex site.The source code for the libraries is also is available at Codeplex.
Lets create a new Silverlight 4 project and add MVVMLight package as a dependent assembly. Remember that you’ll need to have the NuGet package manager installed on your system before starting this demo. Once the initial set of files are generated by Visual Studio 2010, right click on the Reference. If you have NuGet installed, you’ll find an additional option called “Add Library Package Manager”
Select this option and you’ll find the extensions manager popup as shown below. In the top right corner you can type “MVVM Light” in the search box. From the filtered results install the MVVM Light Toolkit package.
This would automatically add the required dll’s based on the type of application (Silverlight / WPF / WP 7). You can cross verify this from the dll’d added to the references folder.
Also a folder called ViewModel is added as part of installing the package. It consists of a dummy MainWindowViewModel and a ViewModelLocator classes. Using NuGet package manager is very convenient.
Modify ViewModel
The MainWindowViewModel class that we had handcrafted in the previous demo needs to be refactored. Many of the boilerplate code that we had written previously is rendered unusable because of the introduction of MVVMLight toolkit. It provides a framework with a set of base classes which perform similar tasks to what we had done in our earlier demo.
I am going to use the same UI as was used in the previous two demos. So I’ll just copy the XAML markup from earlier code. Also the properties exposed by the view model are same along with the command. So I’ll copy those properties and command to the view model class. There is no change to the IDialogService interface and the DialogService concrete implementation of it. So I have copied them over as well.
Lets start with the changes to view model class one by one. First of all we need to inherit from the ViewModelBase class instead of the INotifyPropertyChanged interface that we had used earlier.
public class MainViewModel : ViewModelBase
ViewModelBase class implements many of the features that we had handcrafted in earlier example including raising of the property changed events. The next thing is to replace the DelegateCommand with a RelayCommand provided by the toolkit. The RelayCommand has similar features to that of DelegateCommand and takes two parameters in the form of the method to be executed and a flag which controls whether or not the method can be executed.
SearchCommand = new RelayCommand(SearchNet, () => CanSearchNet());
Also the way we used the notify mechanism for change in property values undergoes a slight modification. We use the RaisePropertyChanged method of the toolkit with the name of the property.
RaisePropertyChanged("HasText");
Once we have made all these changes, our view model code is very precise and does not contain much of the boilerplate code. The next thing we need to do is wire up the view and the view model together. MVVMLight toolkit has the concept of ViewModelLocator whic is like the repository of the view models. We can add this locator as the resource in our application and then bind to individual view model using the data context of the view.
Lets add the ViewModelLocator to the resources of App.xaml.
<Application.Resources>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
</Application.Resources>
Note: Please note that this is already done for us when we installed the toolkit using the NuGet package.
Finally we can databind the view model to the view using xaml as
<UserControl x:Class="MVVMLightGettingStarted.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
DataContext="{Binding Main, Source={StaticResource Locator}}">
That is all we need to do to integrate MVVMLight toolkit into our application. If you run the application now, you’ll get the same output as we had seen on two previous occasions.
Conclusion
It is very easy to integrate MVVMLight in existing application. MVVMLight toolkit is open source project actively maintained by Laurent Bugnion. There are different versions of the dll’s for Silverlight/WPF/WP 7 based on the DotNet framework as well. These include 2, 3.5 and 4 versions. It is quite commonly used framework for MVVM applications. As we saw in this example, it can help us get rid of many of the boilerplate coding. Also it has support for best practices like implementation of ServiceLocator pattern to decouple the view and ViewModel. As many people advocate the use of “code” free code behind, we did not have a single line of code in the MainPage.xaml.cs. I’ll explore other features of MVVM light in future posts.
As always I have uploaded the complete working solution to dropbox. Until next time Happy Programming
Nilesh:
ReplyDeleteExcellent starter article for those who wish to integrate MVVM Light to their current SL projects.
Thanks for the compliments
ReplyDeleteNilesh, google warns users that your page is potentially dangerous. Could it be the ads?
ReplyDelete