Using the MVVM pattern in WPF, is it best to use a 'master' ViewModel and only use that as your DataContext or is it okay to have multiple ViewModels that interact with the view (if that's possible)? Sorry if this is a dumb question; I'm very new to MVVM.
3
votes
Yes, usually there is a hierarchical relationship between ViewModels. That's OK. That relationship should reflect the logical relationship between the Views.
– Federico Berasategui
MVVM Light uses the service locator pattern to assign DataContext.
– Dustin Kingen
Typically I lean towards having a single ViewModel correspond to a single XAML view file. It's perfectly acceptable for a view to have child views (UserControls), and have corresponding child ViewModels however it really depends on your situation. Unfortunately, while your question certainly isn't dumb by any means, it's a bit too vague to be answerable (the only answer is "it depends") and will likely be closed as a result. A better worded example might be, "Here's a specific example of what I'm doing and the problem it poses, how could I achieve my goal of x and resolve my problem of y?"
– mclark1129
Even if it's closed I think you guys have answered it well enough. Also, Romoku mentioned MVVM Light. Right now I'm using the framework found in this tutorial: codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial How does the full version of MicroMVVM stand up to MVVM Light?
– Jason D
1 Answers
3
votes
There's no "one way rules all" approach, but you'll usually see a 1-1 relationship between views and view-models. In other words, one view-model for a view and this view-model is the data-context for the view. It's common to see a "base" view-model that inherited by the other view-models. This is a very simple explanation, but probably a good starting point for a beginner.