WPF use one ViewModel for multiple UserControls

1k views Asked by At

I've searched a lot for an answer for this question, but couldn't quite find an answer.

I have my main Window and 4 different UserControls. The Window is constructed from all 4 UserControls.

I have a class which is the Window's ViewModel.

I wish to set the DataContext of the Window and all 4 UserControls as the Window's ViewModel.

The problem is that writing the class as the control's DataContext creates a new instance of the class, hence, I can't use the containers I'm filling.

Any way of doing that?

1

There are 1 answers

0
Reed Copsey On BEST ANSWER

DataContext gets inherited in WPF.

If you don't set a DataContext for the UserControl, they will automatically inherit their parent's DataContext (the Window), and should use your ViewModel directly.