I have two views that share one observable collection from certain viewmodel, but with different collection view parameters. What is the correct way of implementing it in MVVM Light? Is there any support for non-static VMs? How can I manage their lifetime and dispose them?
There is!
By default objects resolved from the SimpleIoc are singletons. To get around this you need to pass a unique identifier as a parameter of the ServiceLocator.GetInstance method.
See below:
We have two properties returning the same viewmodel. One returns a singleton and the other will return a new instance each time.
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()); }
}
}
Some of Laurent's examples of MVVM Light make use of a ViewModelLocator with static ViewModel instances (singleton-like). Note the ICleanup
interface. Also, non-static VM's usually have to be MEFed in or constructed in the View's constructor.
For ViewModels management usually use IOC pattern. In MVVM Light framework it is a SimpleIoc implementation.
I prefer to use Ninject - http://www.ninject.org/
© 2022 - 2024 — McMap. All rights reserved.