How does a View know what ViewModel to use in WPF?
c#, mvvm, wpf
Solution
There are various options here.
Something has to set the View's `DataContext` to be an instance of the ViewModel. There are lots of options here:
- This can be done directly in xaml (the View just instances the ViewModel directly).
- This can be done in the View's constructor (`this.DataContext = new MyViewModel();`)
- This can be handled via a `DataTemplate`
- A "coordinating" class can wire these together (ie: a separate "presenter" class can construct both and set the `DataContext` appropriately)
The most common are to either have the View define the VM in the xaml (View-first), or to have everything based from a ViewModel-centric point of view, and have WPF automatically create the View based on the bound VM (ViewModel-first).
The former approach is what's used by a lot of toolkits, such as MVVM Light. The latter approach is what I used in my MVVM blog series, and used by some other toolkits.
Problem
Can someone explain how the View and ViewModel are connected? I can't find anywhere the xaml or the xaml.cs for the View that references the ViewModel, nor anything in the ViewModel.cs file that references the View, yet they are somehow connected, and binding members from the ViewModel to the View work. Also, in the constructor of each, there is only the InitializeComponent for the View and a basic constructor for the ViewModel (no declaration/definition of the View). Thanks!