Click here to Skip to main content
15,564,383 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I have this code in my .xaml file:


It works perfectly when ViewModel has a constructor with no parametars, but when I set ViewModel constructor with parametars it won't work.

It throws me an error:

{"'No matching constructor found on type 'ViewModels.ViewModel'. You can use the Arguments or FactoryMethod directives to construct this type.' Line number '15' and line position '10'."}

What I have tried:

It works ONLY when ViewModel constructor has no parametars, but I'm using dependency injecton in my ViewModel so I can't see solution here.

How can I solve this problem, but still have ViewModel constructor with parametars?

Thanks in advance,
Updated 2-Sep-16 7:22am

Share this answer
For a container to inject constructor parameters the object being initialized needs to be initialized from the container.

// Not from container, will not cause any elements to use container
var myWindow = new MyWindow();

// From container, will allow elements to be injected
var myWindow = ServiceLocator.Current.GetInstance<mywindow>();

Now the keyword in the latter example is allows elements to be injected... Because the way you actually have this laid out is not a recommended practice. You want the Window's constructor to actually have the view model injected so that the latter example I provided (or any other resolve) to create the view model.

Use something like this instead:

public ReleaseManagementView(ReleaseManagementViewModel releaseManager)

    DataContext = releaseManager;

This example requires that the ReleaseManagementViewModel be registered with the container as well. If the constructor parameters cannot be found in the container and are not overridden, the resolution on the ReleaseManagementView will fail. If I tried to put this inside the XAML as you have even if everything is registered appropriately, it will still fail because nothing is directing the container to resolve that element.

That's why you get your error... It's not trying to resolve that view model through the container so there's no available constructor trying to do a simple new().
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900