Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF composite Windows and ViewModels

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.

like image 778
Cartesius00 Avatar asked Oct 10 '22 21:10

Cartesius00


1 Answers

There are a few ways to do this.

Inject the VM

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.

DataBind

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} />

Code Behind

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.

like image 93
Zebi Avatar answered Oct 14 '22 03:10

Zebi