WP7 – Sharing data between pages with MVVM

Since the start of my WP7 app, I have leveraged IOC (specifically Ninject) to fill dependencies on my ViewModels following the MVVM Light samples.  To briefly summarize, I have an app level resource called Locator which provides properties for each of my ViewModels.  These properties get the instance from the IOC container. 

Locator:

    public class ViewModelLocator
    {
        public static IKernel Container { get; private set;}

        static ViewModelLocator()
        {
            Container = new StandardKernel(new ViewModelNinjectModule());
        }

        public ITrackViewModel TrackViewModel { get { return Container.Get<ITrackViewModel>(); } }
    }
    public class ViewModelNinjectModule : NinjectModule
    {
        public override void Load()
        {
            Bind<ApplicationState>().To<ApplicationState>().InSingletonScope();
            Bind<ITrackViewModel>().To<TrackViewModel>();
        }
    }

ViewModel:

public class TrackViewModel : ITrackViewModel
{
    public TrackViewModel(ApplicationState appState)
    {
        ApplicationState = appState;
    }
    public ApplicationState { get; set; }
}

Ninject handles filling the constructor dependencies on my ViewModels.  If I need to obtain data from a previous page, the ViewModel will have a constructor parameter of type ApplicationState.  ApplicationState is a POC with properties for each bit of data that I need to pass between pages.

public class ApplicationState
{
    public Customer SelectedCustomer { get; set; }
    public IEnumerable<CartItem> CartItems { get; set; }

}

So to share data between two pages I create a data property in ApplicationState, add an ApplicationState constructor parameter to each ViewModel and set/get the property appropriately.  Only one instance of ApplicationState is created. 

Kevin Wolf blogged about a NavDictionary he uses to pass state between pages.  So if your not using MVVM this is an alternative solution.

One thought on “WP7 – Sharing data between pages with MVVM

Leave a Reply