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?
I think you are a little confused here. You don't need to create
DataContext(s)
for yourviews
explicitly. When yourViewModel
define your View It is also passed down to yourView
as it'sDataContext
.For example if your view is
LoginScreen
your DataContext will bevm:LoginScreenViewModel
. you don't need to create a new object ofvm:LoginScreenViewModel
after LoginScreen is loaded and assign it to view.You may be better off instantiating your view from the view models. Instantiate the view models wherever your CurrentView Content Control is and just set the Content property to the view contained inside the view model. That way they are not being recreated each time you switch views.