Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MvvmCross: Does ShowViewModel always construct new instances?

Whenever I call ShowViewModel, somehow a ViewModel and a View of the requested types are retrieved and are bound together for display on the screen. When are new instances of the ViewModel and View created versus looked up and retrieved from a cache somewhere? If new instances are always created and I choose to make my own cache to prevent multiple instances, then how do I show my cached ViewModel instance?

like image 398
user2395286 Avatar asked May 23 '13 20:05

user2395286


1 Answers

When are new instances of the ViewModel and View created versus looked up and retrieved from a cache somewhere?

Never - for new navigations the default behaviour is always to create new instances.

if... how do I show my cached ViewModel instance?

If for whatever reason you want to override the ViewModel location/creation, then there's information available about overriding the DefaultViewModelLocator in your App.cs in:

  • MVVMCross Passing values to ViewModel that has 2 constructors
  • http://slodge.blogspot.co.uk/2013/01/navigating-between-viewmodels-by-more.html

Put simply, implement your code:

public class MyViewModelLocator
  : MvxDefaultViewModelLocator
{
    public override bool TryLoad(Type viewModelType, IDictionary<string, string> parameterValueLookup,
                             out IMvxViewModel model)
    {
        // your implementation
    }
}

then return it in App.cs:

protected override IMvxViewModelLocator CreateDefaultViewModelLocator()
{
    return new MyViewModelLocator();
}

Note that older posts like How to replace MvxDefaultViewModelLocator in MVVMCross application are still conceptually compatible - but the details in those older posts are now out of date.

like image 68
Stuart Avatar answered Sep 21 '22 22:09

Stuart