What I have is three different views. I have view models for each of these views. What I do is set the datacontext of the view to a new instance of the respective view model and this works like shown below:
public LoginScreen()
{
InitializeComponent();
DataContext = new LoginScreenViewModel();
}
This works as desired. Everything binds correctly and such.
Now, I have each of my views set up as UserControls. I have my Window that has datatemplates for each of my views as shown below:
<Window.Resources>
<DataTemplate DataType="{x:Type vm:LoginScreenViewModel}">
<v:LoginScreen/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:MainWindowViewModel}">
<v:MainWindow/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:AboutScreenViewModel}">
<v:AboutScreenView/>
</DataTemplate>
</Window.Resources>
I display the views like so:
<Grid>
<ContentControl Content="{Binding CurrentView}"/>
</Grid>
This allows me to create viewmodels in my window's view model set them as the CurrentView and the view associated with that view model is displayed in the window. This all works correctly.
My problem is that if I switch views, all of the information that is stored in a View's ViewModel is destroyed. My question is, how to I bind the datacontext of each view to the viewmodel that is creating it instead of to a new instance in the code behind?