Injecting ViewModels to Views using a custom ViewModelLocator in Windows Phone
Join the DZone community and get the full member experience.
Join For FreeIn one of my previous posts (IoC for Windows Phone: Ninject I have shown a simple IoC and DI tutorial using Ninject. In this tutorial will be based on previously developed code and extended that with a custom ViewModelLocator to bind ViewModels directly to Views. Hopefully, it will allow you to insert ViewModels with dependencies injected easier and faster for your Windows Phone or Silverlight applications.
As usual, without any introductions lets get directly to the
development environment and to the previously created code. Before we
begin, we need to remove one line of code from our View’s
codebehind(constructor)
public class ViewModelLocator { public NinjectSampleViewModel NinjectSampleVm { get { return IoCContainter.Get<NinjectSampleViewModel>(); } } }
Adding ViewModelLocator as an Application Resource
Next step is to add this ViewModelLocator to the App.xaml as a Resource. It will give us an option to access it as a StaticResource from the Views. So add the following lines to App.xaml file:
<Application.Resources> <EugeneDotnetIoCSamples:ViewModelLocator x:Key="ViewModelLocator" /> </Application.Resources>
Adjusting the View
Finally, let’s open the View and modify that a little bit by adding the line bellow to phone:PhoneApplicationPage element:
DataContext="{Binding NinjectSampleVm, Source={StaticResource ViewModelLocator}}"This line binds NinjectSampleVm to DataConext property of View using ViewModelLocator resource.
Results
The result should be similar to the result from the previous tutorial, but now the ViewModel is inserted via ViewModelLocator. I think this approach is suitable for a large application development, because it allows you to decouple ViewModel with dependencies injected to a single ViewModelLocator class to use it for testability(i.e Unit Tests). Also this approach significantly decreases the amount of code inside your application.
You can find the source code inside EugeneDotnetIoCSamples Project inside EugeneDotnetWPCodeSamples GitHub project:
Source: http://www.eugenedotnet.com/2011/11/injecting-viewmodels-to-views-using-a-custom-viewmodellocator/
Opinions expressed by DZone contributors are their own.
Comments