Click here to Skip to main content
14,984,183 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:

I am trying to create a new instance of my class, but I am not able to.
What am I doing wrong?

public ExampleClass : Window {   

    public ExampleClass(MyViewModel viewModel) {

        DataContext = viewModel;

private void btnNew_Click(object sender, RoutedEventArgs e) {

    ExampleClass newExampleClass = new ExampleClass();

I know it needs a parameter, but which?
What am I not grasping here?

What I have tried:

I tried adding viewModel, as well as MyViewModel viewModel as parameters - neither works.
I've tried Googling and reading documentation, but the answer is eluding me. :-)

Thank you for any assistance provided!
Updated 22-Jun-21 23:52pm

Your constructor expects an instance of the class MyViewModel. You either need to pass in an existing instance of that class, or a new instance of that class.
MyViewModel viewModel = GetTheViewModelInstanceFromSomewhere();
ExampleClass newExampleClass = new ExampleClass(viewModel);
MyViewModel viewModel = new MyViewModel();
ExampleClass newExampleClass = new ExampleClass(viewModel);
If you're creating the instance from code within an instance the ExampleClass and you want to pass in the current viewmodel, then you'll need to cast the DataContext since you haven't stored it anywhere else.
MyViewModel viewModel = DataContext as MyViewModel;
ExampleClass newExampleClass = new ExampleClass(viewModel);

NB: You will not be able to use the WPF designer with this window, since it has no way to create an instance of your window class.
Flidrip 23-Jun-21 7:15am
Thanks @Richard Deeming, that makes sense!

You defined your ExampleClass to have a parametered Constructor (hiding the parameterless one in doing so).

The only way you are going to create a new instance of your class is by passing it an instance of the MyViewModel class.

Doing the following in the event handler btnNew_Click should remove any compilation error :

MyViewModel viewModel = null;
ExampleClass newExampleClass = new ExampleClass(viewModel);

You still need however to figure out how to create a valid instance of the class MyViewModel, I defaulted it to null not knowing the context of your code.
Hopefully you have an idea.

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