I have a WPF Window which contains few UserControls, those controls contain another. And now, what is the most principal way how to create ViewModel for this Window and where to bind it.
I do expect that one firstly needs to create ViewModel for each of sub-controls.
There are a few ways to do this.
Inject the VM
I would recommend this method.
If your window is created in the
Appclass likeI would assign the VM before showing the window:
If one of your controls needs an own view model assign the VM wile creating the control instance.
DataBind
If you want to set the VM of a control you can bind the
DataContextproperty to an VM instance provided by the surrounding VM.Code Behind
You may set the VM using the init method in code behind like
You may use a trick if you don’t want to create a VM for your main page:
and just use the code behind class as VM.