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!
If you use Binding instead then you define a property of the ViewModel. So the View knows about the property of the ViewModel. It's just that Binding uses Reflection (not type safe) but the coupling is the same.
The other approach to bind the View and Viewmodel in View First Approach is in the xaml itself as shown in the figure below. I am setting the datacontext in the . xaml of the View itself. To set the datacontext in this way the ViewModel class need to have a default constructor.
No that is fine; each object should be a ViewModel in its own right.
For a best mvvm pattern implementation each view must have the own viewmodel, and don't share anythings with other.
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.DataContext = new MyViewModel();
)DataTemplate
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.
A "clean" way for connecting the views to the view-models would be...
When you create the views, for each view, set its DataSource to its view-model:
E.g.
public class App { private void OnAppStart() { var model = new MainModel(); var vm = new MainVM(); var view = new MainWindow(); vm.Model = model; view.DataSource = vm; view.Show(); } }
When the model you are viewing changes, update the VM:
public class MainVM { private void OnSelectedModelItemChanged() { this.SelectedItem = new ItemVM(); this.SelectedItem.Model = this.SelectedModelItem; } }
And use data templates to make view select the correct sub views for each 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