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()); }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With