当视图模型的构造函数中有参数时,如何将 ViewModel 连接到视图?
我正在使用 Prism 和 Unity 使用 MVVM 模式重写 WPF 应用程序。大多数视图通过 DataContext 属性连接到 VM,如下所示:
<UserControl.DataContext>
<VM:RibbonViewModel/>
</UserControl.DataContext>
问题是,当 ViewModel 的构造函数中有参数时,此方法将不起作用。
public RibbonViewModel(IEventAggregator eventAggregator)
{
this.eventAggregator = eventAggregator;
}
我收到错误:
类型“RibbonViewModel”不可用作对象元素,因为它不是公共的或未定义公共无参数构造函数或类型转换器。
当有参数时,如何将虚拟机连接到视图?
I'm using Prism and Unity to rewrite a WPF application using the MVVM pattern. Most of the Views are connected to the VM via the DataContext property, like so:
<UserControl.DataContext>
<VM:RibbonViewModel/>
</UserControl.DataContext>
The problem is that this method will not work when there is a parameter in the ViewModel's constructor.
public RibbonViewModel(IEventAggregator eventAggregator)
{
this.eventAggregator = eventAggregator;
}
I get the error:
Type 'RibbonViewModel' is not usable as an object element because it is not public or does not define a public parameterless constructor or a type converter.
How do I connect the VM to the View when a parameter is there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以查看WPF 应用程序框架 (WAF) 的示例应用程序。在这些示例中,IoC 容器(在您的例子中是 Unity)负责创建 ViewModel。这样 ViewModel 就可以有构造函数参数。 IoC 容器还负责将视图与视图模型结合在一起。也许这也是您的 ViewModel 设计的一个选项。
You might have a look at the sample applications of the WPF Application Framework (WAF). In these examples the IoC Container (in your case its Unity) is responsible to create the ViewModels. This way a ViewModel can have constructor parameters. The IoC Container is also responsible to bring the View with the ViewModel together. Maybe this is an option for your ViewModel design as well.
考虑使用 ViewModelLocator。在上面的例子中,您不是将数据上下文绑定到 ViewModel,而是绑定到一个定位器,该定位器知道如何从(统一)容器解析 ViewModel,并在此过程中将任何依赖项注入到构造函数中。有一篇博客文章总结了 John 的实现Papa 和 Glenn Block(棱镜背后的人之一)。
我相信 EventAggregator 默认情况下已在容器中注册,因此当您从容器解析 VM 时,它应该自动与 VM 连接。
我应该提到上面博客中的代码 正在使用 MEF。我相信这个博客有一个使用 unity 的 codeplex 示例
Consider using a ViewModelLocator. Rather than binding the datacontext to the ViewModel in your case above, you bind to a locator which knows how to resolve the ViewModel from the (unity) container and in the process inject any dependencies into the constructor. There's a blog posting summarizes an implementation by John Papa and Glenn Block (one of the people behind prism).
I believe the EventAggregator is registered with the container by default, so it should be auto-wired with the VM when you resolve the VM from the container.
I should mention the code from the above blog is using MEF. This blog I believe has a codeplex example using unity
我不使用 Unity 或 Prism。但是,为什么不能这样做:
您可以在设置的用户控件上有一个依赖属性。在设置此依赖属性的值时,您可以设置数据上下文。
I don't use unity or prism. But, why can't you just do this:
You can have a dependency property on the user control which is set. On setting of value of this dependency property, you can set the datacontext.