将参数传递给 ViewModel 构造函数
是否可以将参数传递给 ViewModel 构造函数?然后,我将使用此参数来初始化属性和/或在 ViewModel 中执行其他操作。
使用 WinForms,我可以做
public MyForm(MyParamType myParam) { MyFormProperty = myParam; //etc. }
如何在 MVVM 模式/使用 MVVM Light 中做类似的事情?
任何建议都将受到欢迎。提前致谢。
Is it possible to pass a parameter to the ViewModel constructor? I would then use this parameter to initialise a property and/or do other operations in the ViewModel.
With WinForms I could do
public MyForm(MyParamType myParam) { MyFormProperty = myParam; //etc. }
How do I go about doing something similar in the MVVM pattern / using MVVM Light?
Any suggestions would be most welcome. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议使用 IoC 容器并配置容器以在构建时提供参数。
例如,在 WPF 中,UserControl 的典型代码隐藏如下所示:
StructureMap 为我创建 MyListViewModel,因为默认情况下它会搜索最贪婪的构造函数,然后提供依赖项。在我的 StructureMap 配置中,我可以指定为 MyListViewModel 提供构造该对象时所需的任何参数。
使用像 StructureMap 这样的容器,我不必“新建”对象。曾经。
I would recommend using an IoC container and configuring your container to supply the parameter upon construction.
For instance, here's what a typical code-behind to a UserControl looks like for me in WPF:
StructureMap creates the MyListViewModel for me because by default it searches for the greediest constructor and then provides the dependencies. In my StructureMap configuration, I can specify that the MyListViewModel be provided with whatever parameters are necessary upon construction of that object.
With a container like StructureMap, I don't have to "new" up objects. Ever.
如果你使用的是 MVVM light(即使你不是我猜的),你可以向 Messenger 注册一个消息处理程序,它接受你的构造函数参数(或其元组),并在你需要“重建”它时更新 VM。
If you're using MVVM light (even if you're not I guess) you could register a message handler with the Messenger that takes your constructor parameters (or a tuple thereof) and updates the VM whenever you need to "reconstruct" it.
由于所有视图模型在定位器上都是静态的,因此您可以直接访问这些属性,而无需更改构造函数。
Since all the view models are static on the locator, you can just access those properties already without changing a constructor.
我不明白为什么你不能自己创建视图模型。您始终可以创建自己的视图模型。如果 MVVM Light 提供了一个视图模型,那么您始终可以继承该视图模型并创建一个重载的构造函数。
I dont understand why you cant just create the viewmodel yourself. You can always create your own viewmodel. If there is a viewmodel provided by MVVM Light then you can always inherit from that one and create an overloaded constructor.