How to I connect a ViewModel to a View when the view model has parameters in the constructor?

江枫思渺然 提交于 2019-11-30 21:10:30

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.

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

I don't use unity or prism. But, why can't you just do this:

userControl.DataContext = ribbonViewModelInstance;

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.

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