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

I am quite familiar with the MVVM pattern quite recently. I am using MVVMLight. I am wondering how several unique instances of ViewModel with MVVM Light. For exmaple, I have an application that can open n number of windows. Everyone uses the same Viewmodel. I am curious in MVVM that it is best to give them their own instance.

If I follow the MVVM Light example, the ViewModeLocator will only have a static instance in which each window will be used.

Thanks in advance.

+4
source share
2 answers

You are not required to use ONLY static view models in the view model locator. This approach only makes sense if your views use the same instance of the view model. For your scenario, you simply update an instance of your view model and assign it to the DataContext property of each window you create.

public void ShowChildWindow(Window parent) { var window = new WindowView(); window.DataContext = new ViewModel(); window.Show(); } 
+5
source

Easy:

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

When enabling ServiceLocator, make sure that the GetInstance call passes a unique value to the method. In the above example, I am passing a pointer.

I really wonโ€™t build your objects manually, as this will defeat the point with the Injection Dependency container in MVVM Light.

+8
source

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


All Articles