Over a million developers have joined DZone.

Injecting ViewModels to Views using a custom ViewModelLocator in Windows Phone

DZone's Guide to

Injecting ViewModels to Views using a custom ViewModelLocator in Windows Phone

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

In 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:

    <EugeneDotnetIoCSamples:ViewModelLocator x:Key="ViewModelLocator" />

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.


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:

eugenedotnet github windows phone project

Source: http://www.eugenedotnet.com/2011/11/injecting-viewmodels-to-views-using-a-custom-viewmodellocator/

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}