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.
I would recommend this method.
If your window is created in the App
class like
var window = new MyWindow();
window.Show();
I would assign the VM before showing the window:
var window = new MyWindow();
window.DataContext = GetDataContextForWindow();
window.Show();
If one of your controls needs an own view model assign the VM wile creating the control instance.
If you want to set the VM of a control you can bind the DataContext
property to an VM instance provided by the surrounding VM.
<Controls:MyControl DataContext={Binding MyControlsVm} />
You may set the VM using the init method in code behind like
public MyWindow()
{
InitializeComponent();
DataContext = CreateViewModel;
}
You may use a trick if you don't want to create a VM for your main page:
public MyWindow()
{
InitializeComponent();
DataContext = this;
}
and just use the code behind class as VM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With