I am using Ninject to inject view model instances into the DataContext property of each view, to avoid using a ServiceLocator, and am using the following syntax inside a NinjectModule as suggested here:
public class TestingModule : NinjectModule
{
public override void Load()
{
Bind<MainPage>().ToMethod(ctx => new MainPage() { DataContext = new MainPageViewModel() }).InSingletonScope();
}
}
If I use:
var x = Kernel.Get<MainPage>();
Then the DataContext property inside x is set to an instance of MainPageViewModel, which is great.
The problem is that the Application does not get the view instances from the DI container when navigating to pages or when starting up, so the DataContext property is never set in any of the views when running the app on a device or inside the emulator.
Does anyone know how I can intercept the creation of views so that I can force the app to retrieve view instances from the DI container?
Have a look at one of the various MVVM frameworks like Caliburn Micro instead of reinventing the wheel. They did a great job making it easy to tie views and view models together while using an IoC container.
Here is a blog post about how to setup Caliburn Micro with Ninject on WP7: http://devlicio.us/blogs/derik_whittaker/archive/2011/07/08/using-ninject-with-commonservicelocator-with-caliburn-micro-on-wp7.aspx