Imagine having a View which will show multiple steps of data gathering. Based on decisions in the previous step, the sequence or specific instances of the following steps will vary.
Following MVVM purist best practices, I figure having a list of ViewModels in the outer ViewModel is the way to go about this, and let the outer View bind a custom tab control (or similar) to that.
This brings me to two aspects of this which are unclear to me:
Point One: "Which came first?"
The outer View / ViewModel combo would probably be "View First". That is, a view either receives a ViewModel, or instantiates one.
But when it comes to the list of ViewModels within this outer ViewModel: Where do their respective Views come from? Which entity is responsible for picking the best view for each of these?
I'm not all comfortable with alternating between "View First" and "ViewModel First" like this.
Point Two: Communication between ViewModels
When one of the inner ViewModel steps are completed, e.g. at the click of a "Save" or "Next" button, a command should be fired to that inner ViewModel, and then the next should be shown.
This requires the outer ViewModel to:
be able to pick up on the Save command sent to the inner ViewModel
be able to access the data within the inner ViewModel.
How would one normally go about this? Is it considered a bad practice to tie the inner and outer ViewModel together with events?
1) In my understanding MVVM
always says ViewModels first
and Views
are bound to already instantiated ViewModels
. For all inner/outer ViewModels.
Where do their respective Views come from? Which entity is responsible for picking the best view for each of these?
In WPF I prefer to use DataTemplating
for this reason. In app.xaml
or some other application-wide resource file you define DataTemplates
specific to each of your ViewModels. In Views
you put a binding to ViewModel into ContentPresenter
and DataTemplating bring View there. Sample:
App.xaml:
<Application.Resources>
<DataTemplate DataType="{x:Type local:OuterViewModel}">
<local:OuterView />
</DataTemplate>
<DataTemplate DataType="{x:Type local:InnerViewModel}">
<local:InnerView />
</DataTemplate>
<Application.Resources>
OuterView.xaml:
<Grid>
<!-- Assuming OuterViewModel has a property named 'InnerViewModel' -->
<ContentPresenter Content="{Binding InnerViewModel}" />
</Grid>
2)
be able to pick up on the Save command sent to the inner ViewModel
I would put SaveCommand
on OuterViewModel
be able to access the data within the inner ViewModel.
I would have a reference to each inner ViewModel in OuterViewModel
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