Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have Multiple unique instances of ViewModel using MVVM Light?

I am fairly new to following the MVVM pattern. I am using MVVMLight. I am wondering how have multiple unique instances of the ViewModel with MVVM Light. For exmaple I have an application that can open n number of windows. Each uses the same Viewmodel. I am curious in MVVM whats the best practive to give them there own instance.

If I follow the MVVM Light example the ViewModeLocator will have only a static instance which each window will end up using.

Thanks in advance.

like image 631
jballing Avatar asked Dec 06 '22 11:12

jballing


1 Answers

Easy:

public EndingViewModel EndingViewModel
{
    get 
    { 
      return ServiceLocator.Current.GetInstance<EndingViewModel>(Guid.NewGuid().ToString()); 
    }
}

When resolving from the ServiceLocator make sure the call to GetInstance passes in a unique value to the method. In the above example I pass in a guid.

I really wouldn't build your objects manually as this defeats the point of having the Dependency Injection container in MVVM Light.

like image 102
Faster Solutions Avatar answered Dec 11 '22 09:12

Faster Solutions