This project is read-only.

ViewModel Instantiation

May 14, 2013 at 9:41 PM
New to StyleMVVM and so far its great, only I'm having some issues with when/how the ViewModels are getting initialized. I'm doing an application that follows close to the Grid App Model and the issue I'm having is when I navigate pages the ViewModels are recreated. I just need them to be created once on initial navigation / import. They inherit from PageViewModel and my views are LayoutAwarePage. Is there some export attribute or something I need to apply to make it so these are only created once? Hopefully this is enough of an explanation if not let me know and I can expand on what I'm doing more.
May 14, 2013 at 10:09 PM
Hi KJ,

You are correct it is as easy as adding an Attribute, by default all ViewModels are defined as non shared (each call gets a new one). To augment the export behavior you can add one of these attributes to the top of your ViewModel

[Shared] - While the instance is alive (i.e. not garbage collected) it will be re-used. Once the object goes out of scope and has been collected a new instance will be created next time the export is needed.

[Shared(Permanent = true)] - Once created a shared Permanent instance will be kept for the lifetime of the container, for every call after that needs that export it will be reused.

[Cached] - Marking an export as Cached means it will be re-used while it's cache window is applicable. You can make the cache window be absolute or sliding.

It sounds to me like you probably want the [Shared(Permanent = true)] option.

Let me know if this helped or you have more questions

-Ian
May 14, 2013 at 10:19 PM
This is exactly what I needed! Thank you for the quick response, I used [Shared(Permanent=true)] and it works great.