Search code examples
.netxamlnavigationwindows-store-appswindows-store

Prism App Navigation Causes "Object Reference" Error


I created a new Windows Store app project and added Prism to it. I setup the Main page to use the common infrastructure, and it all works great. I create a second Test page in the Views folder, with a name TestPage, that looks like the following:

<Infrastructure:VisualStateAwarePage
 .
 .
    xmlns:Infrastructure="using:Microsoft.Practices.Prism.StoreApps"
    Infrastructure:ViewModelLocator.AutoWireViewModel="True"
    >

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

    </Grid>
</Infrastructure:VisualStateAwarePage>

And has a simple model in the ViewModels folder:

public class TestPageViewModel { } 

When I navigate to the page using the navigation service (I have my navigation service in the Unity Container as described in the MSDN documentation), I get "Object reference set to an instance of an error." No stack trace to point where, no more details than that... any idea why I am getting that error? Again, the test page view and model are setup the same as my main page, but main works initially, yet I can't get the test to load on redirection.

Any idea why?


Solution

  • This is something that often catches me as well, and not very well explained in the multitude of examples out there.

    Make sure that when you set up your IoC container in your App.xaml.cs file, you also tell the ViewModelLocator to use Unity to look for your View Model instances with the SetDefaultViewModelFactory() method:

    private readonly IUnityContainer _container = new UnityContainer();
    
    protected override void OnInitialize(IActivatedEventArgs args)
    {
        base.OnInitialize(args);
    
        _container.RegisterInstance<INavigationService>(NavigationService); 
        _container.RegisterInstance<ISessionStateService>(SessionStateService);
        _container.RegisterInstance<IFlyoutService>(FlyoutService);
        // etc
    
        // Tell the Unity ViewModelLocator to use the Unity container to resolve ViewModels
        ViewModelLocator.SetDefaultViewModelFactory((viewModelType) => _container.Resolve(viewModelType));
    }
    

    Hope that helps.