wpf 如何使用 MVVM Light 拥有多个唯一的 ViewModel 实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13039126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to have Multiple unique instances of ViewModel using MVVM Light?
提问by jballing
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.
我对遵循 MVVM 模式还很陌生。我正在使用 MVVMLight。我想知道如何使用 MVVM Light 拥有多个独特的 ViewModel 实例。例如,我有一个可以打开 n 个窗口的应用程序。每个都使用相同的 Viewmodel。我很好奇 MVVM 是什么给他们提供自己的实例的最佳实践。
If I follow the MVVM Light example the ViewModeLocator will have only a static instance which each window will end up using.
如果我遵循 MVVM Light 示例,则 ViewModeLocator 将只有一个静态实例,每个窗口最终都会使用该实例。
Thanks in advance.
提前致谢。
回答by Faster Solutions
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.
从 ServiceLocator 解析时,请确保对 GetInstance 的调用将唯一值传递给该方法。在上面的例子中,我传入了一个 guid。
I really wouldn't build your objects manually as this defeats the point of having the Dependency Injection container in MVVM Light.
我真的不会手动构建你的对象,因为这违背了在 MVVM Light 中拥有依赖注入容器的意义。
回答by bugged87
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.
您不必在视图模型定位器中仅使用静态视图模型。只有当您的视图共享相同的视图模型实例时,这种方法才有意义。对于您的场景,您只需新建一个视图模型实例并将其分配给您创建的每个窗口的 DataContext 属性。
public void ShowChildWindow(Window parent)
{
var window = new WindowView();
window.DataContext = new ViewModel();
window.Show();
}

