Retain VM state after switching views

Feb 5, 2014 at 7:14 AM
Edited Feb 6, 2014 at 9:14 AM
Hi Tony,

I'm struggling with a simple problem and maybe you can point me in the right direction? I have a view (manage_view) with multiple button options that will navigate (set a frame's source) to new views (manage_import_view, manage_scanners_view, etc). Each view has its own VM.

For each of the views I set the datacontext to the VM by using a locator. The locator injects a ServiceAgent into the VM.

The problem is that when I navigate to the other views, the state of the previous view is lost. For instance I'd do an import on the Manage_Import_View and bind to properties on the VM. When I navigate to Manage_Scanners_View and then back to the Manage_Import_View, the properties that I bound to, is lost.

I understand what is happening but Im not sure how to resolve it. How do I keep the state of the ManageViewModel throughout all the views?

Looking forward to your thoughts on this.

Thank you
Feb 19, 2014 at 5:20 AM
Edited Feb 19, 2014 at 5:21 AM
Any comments?
Thanks
Feb 19, 2014 at 8:56 PM
I believe I answered a question similar to yours, on maintaining state between view models when using navigation. The issue is that view models are candidates for garbage collection once they are navigated away from. See my answer in this thread: https://simplemvvmtoolkit.codeplex.com/discussions/267069. There is a link to a zip file with a sample you can look at. Let me know if this helps.

Cheers,
Tony
Marked as answer by charlie_138 on 2/20/2014 at 2:59 PM
Feb 20, 2014 at 10:59 PM
Brilliant! Thank you so much.

I saw that in your demos but totally overlooked the logic of it. I had to comment out the pageValues.Remove(..); bit in the UserControl_Loaded() method otherwise my values were lost on second hit of the uc

This just solved such a large issue in my project.

Thanks again.
Feb 25, 2014 at 12:07 PM
Hi Tony, I have another question from using your suggestion..

If I want to keep a list/container of global/shell-wide properties and values, can I use the same approach by adding them to the PageValues dictionary?
I have some values that multiple VMs should be able to access. I don't want to pass these values in the constructor but rather have them readily available when needed.

At the moment I have a ShellVM that manages the PageValues. Any other VM that wants to set or get a PageValue does so by sending a message. The ShellVM responds to the message and sends the value back or insert the new value. In other words the ShellVM manages the CRUD of PageValues.

I have a feeling there should be another way to manage this.

Thanks for taking the time to help me out.