Static ViewModels vs instanced ViewModels
Asked Answered
G

3

6

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?

Gough answered 13/5, 2011 at 10:39 Comment(2)
Are you using a DI container such as Unity or MEF?Dewy
No, I use basic MVVM Light template.Gough
F
1

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()); }
    }
}
Ferdinande answered 9/8, 2013 at 12:6 Comment(0)
W
0

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.

Words answered 7/6, 2011 at 20:38 Comment(0)
T
0

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/

Tomtit answered 9/8, 2013 at 8:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.