If my MainWindow has the following code:
<Window x:Class="DaveMVVM.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewModel ="clr-namespace:DaveMVVM.ViewModel"
xmlns:view="clr-namespace:DaveMVVM.View"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<viewModel:MainWindowViewModel x:Key="Vm" />
</Grid.Resources>
<view:MyFirstView />
</Grid>
</Window>
then can I assume I can't change the View from MyFirstView... For example, I will want my MainWindow to just be a frame which practically only hosts the Menu
, and depending on what option they select from the Menu
will depend on what View is displayed.
So, my 2 questions are
1) Am I correct in thinking that the above example will not work since the View is hard coded.
2) Do I have to use DataTemplates which are bound to my MainWindowViewModel, and then have a DataTemplate created for each View?
Thank you.
You would do this as follows:
Your MainWindowViewModel exposes a property
CurrentContent
. It returns a common base type of all your view models:Based on the selection of the user, you would set that property to the corresponding view model.
Your main view would contain a
ContentControl
that is bound to this property:Finally, your view - or a separate resource dictionary - would have to contain data templates for each of the possible content view-models: