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

I use Prism and Unity to rewrite a WPF application using the MVVM pattern. Most views are connected to the virtual machine through the DataContext property, for example:

<UserControl.DataContext> <VM:RibbonViewModel/> </UserControl.DataContext> 

The problem is that this method will not work if there is a parameter in the ViewModel constructor.

 public RibbonViewModel(IEventAggregator eventAggregator) { this.eventAggregator = eventAggregator; } 

I get an error message:

The type "RibbonViewModel" cannot be used as an element of an object because it is not public or does not define an open constructor without parameters or a type converter.

How to connect a virtual machine to a view when there is a parameter?

+4
source share
3 answers

You can take a look at the WPF Application Framework (WAF) sample applications. In these examples, the IoC container (in your case, its Unity) is responsible for creating ViewModels. Thus, the ViewModel can have constructor options. The IoC container is also responsible for sharing View with the ViewModel. Perhaps this is an option for your ViewModel design.

+5
source

Consider using ViewModelLocator. Instead of binding the datacontext to the ViewModel in your case above, you are bound to a locator that knows how to enable the ViewModel from the container (unity) and in the process to embed any dependencies in the constructor. There, the blog posts a summary of John Papa and Glenn Block (one of the people behind the prism).

I believe that EventAggregator is registered in the container by default, so it should be automatically connected to the VM when resolving the virtual machine from the container.


I should mention that the code from the above blog uses MEF. This blog . I believe the code example using unit

+2
source

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

 userControl.DataContext = ribbonViewModelInstance; 

You may have a dependency property in the user control that is installed. When setting the value of this dependency property, you can set the datacontext.

+1
source

Source: https://habr.com/ru/post/1336419/


All Articles