如何在 WPF 应用程序中将参数传递给 ViewModel 的构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13107064/
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 do I pass parameter to ViewModel's constructor in a WPF application?
提问by Chen
I see people suggests using Messenger/EventAggregator to pass parameter to ViewModel when "current" target is changed, but it doesn't work on my case.
我看到人们建议在“当前”目标更改时使用 Messenger/EventAggregator 将参数传递给 ViewModel,但它不适用于我的情况。
Say I have a ViewModel class like this:
假设我有一个这样的 ViewModel 类:
class CustomerViewModel
{
CustomerViewModel(int customerId) {}
}
And:
和:
- I have views of same type in the application shell at the same time.
- For each view, there is a unique CustomerViewModel instance for it. Each CustomerViewModel instance can have different customerId. (which is similar to Visual Studio IDE, multiple document opened at the same time)
- 我同时在应用程序外壳中有相同类型的视图。
- 对于每个视图,都有一个唯一的 CustomerViewModel 实例。每个 CustomerViewModel 实例可以有不同的 customerId。(类似于Visual Studio IDE,同时打开多个文档)
I don't want to write code like "this.DataContext = new CustomerViewModel(id)" in my View class. What's the MVVM way to handle such case?
我不想在我的 View 类中编写像“this.DataContext = new CustomerViewModel(id)”这样的代码。处理这种情况的 MVVM 方法是什么?
Thanks.
谢谢。
采纳答案by Blachshma
There are a few ways to handle this case, first - decide if you're using a View first or View Model firstapproach.
有几种方法可以处理这种情况,首先 - 决定您是使用View first 还是 View Model first方法。
Using the EventAggregator is a valid option.
使用 EventAggregator 是一个有效的选项。
Another option is to have your ViewModel implement an interface and then use some IoC/DIsuch as MEFor Unity to get the instance of the ViewModel. Using this method, you can define an Initalize(int Id)function which you know the ViewModel must implement.
You don't need your View to know the CustomerViewModel class, only the interface.
另一种选择是让您的 ViewModel 实现一个接口,然后使用一些IoC/DI(例如MEF或 Unity)来获取 ViewModel 的实例。使用此方法,您可以定义一个Initalize(int Id)您知道 ViewModel 必须实现的函数。您不需要您的视图来了解 CustomerViewModel 类,只需了解界面。
I should note that if you are using some kind of DI, you can always inject that parameter to the ViewModel. IIRC in Unity this can be done a bit easier then in MEF (you simply register the value and then create the ViewModel which depends on that type).
我应该注意,如果您使用某种DI,您总是可以将该参数注入到 ViewModel 中。在 Unity 中,这可以比在 MEF 中更容易完成(您只需注册该值,然后创建取决于该类型的 ViewModel)。

