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

女生的网名这么多〃 提交于 2020-01-01 05:50:55

问题


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.


回答1:


You are not obliged to use ONLY the static view models in the view model locator. That approach only makes sense if your views are sharing the same view model instance. For your scenario, you would simply new up 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();
}



回答2:


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.



来源:https://stackoverflow.com/questions/13039126/how-to-have-multiple-unique-instances-of-viewmodel-using-mvvm-light

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!