I’m currently working on an app and am having some “architectural confusions”.
I’m implementing my own (very simple) MVVM pattern, which ideally will only have one instance and will be updated about every 60 seconds.
When doing Xaml (Silverlight) in Windows Phone 7 on a previous App, I was able to put the ViewModel in my App class (where the application begins), I was then able to access this one model throughout the whole app after the initial loading process was done.
I’ve been searching the interwebs and downloading tutorials/samples to see if anywhere can provide a definitive answer for Windows 8 Store Apps.
And now I’m wondering if this is the correct way of working in Windows 8 Store Apps?
Here are a couple of ways of working that I have explored:
- Having the ViewModel in the MainPage.cs file, then on each navigate method I have been passing the ViewModel as a page parameter for the next page to use.
- Having the ViewModel in the App.cs file, tried this but can’t seem to access this from any other page
- Having a static ViewModel class, which holds all of the information for the application. Not seen any other projects/samples which have done this so I’m a bit reluctant to “break away” from the norm and do this.
I’m sure this has been thought about and there is a way of doing this in Windows 8 Store Apps, however I’m stuggling to find a definitive answer and many of the official (MSDN) samples/tutorials that I have come across do not really address this issue. Many of the samples seem to cover very small aspects of the available APIs.
In summary: How can I build a Windows 8 Store Application and have one ViewModel that I all pages can bind to/use throughout the whole application?? Would this require an architectural change in terms of the Application and how the data is stored or is there a way i’ve missed that can make my ViewModel global?
Thanks again 🙂
In general most applications use a different view model for each page, so you don’t often see examples with a shared view-model. It may be better using a separate view model for each view (with page specific code), but a shared data model.
If you really want to make your ViewModel shared between all pages you could try a static ‘Instance’ property on your ViewModel (rather than a static class).
For example,