Static ViewModels and instanced ViewModels

I have two views that share the same observable collection with a specific view model, but with different collection view options. What is the correct way to implement it in MVVM Light? Is there any support for non-static virtual machines? How can I manage and manage my life?

+6
source share
3 answers

There is!

By default, objects allowed from SimpleIoc are single. To get around this, you need to pass a unique identifier as a parameter to the ServiceLocator.GetInstance method.

See below:

We have two properties that return the same presentation model. One returns singleton, and the other returns each new instance.

class ViewModelLocator { static ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); if (ViewModelBase.IsInDesignModeStatic) { SimpleIoc.Default.Register<IDataService, Design.DesignDataService>(); } else { SimpleIoc.Default.Register<IDataService, DataService>(); } SimpleIoc.Default.Register<MainViewModel>(); SimpleIoc.Default.Register<SecondViewModel>(); } public MainViewModel MainAsSingleton { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } } public MainViewModel MainAsDiffrentInstanceEachTime { get { return ServiceLocator.Current.GetInstance<MainViewModel>(Guid.NewGuid().ToString()); } } } 
+1
source

Some Laurent examples from MVVM Light use ViewModelLocator with static instances of ViewModel (single-user). Pay attention to the ICleanup interface. In addition, a non-static virtual machine typically needs to be MEFed in the view constructor or built.

0
source

To control ViewModels, the IOC template is usually used. In the MVVM Light framework, this is an implementation of SimpleIoc.

I prefer to use Ninject - http://www.ninject.org/

0
source

Source: https://habr.com/ru/post/888027/


All Articles