DataContext binding

2019-08-14 03:01发布

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?

2条回答
走好不送
2楼-- · 2019-08-14 03:19

I think you are a little confused here. You don't need to create DataContext(s) for your views explicitly. When your ViewModel define your View It is also passed down to your View as it's DataContext.

Don't assign a DataContext explicitly and try check the DataContext of a view after it is loaded. It will be the ViewModel that actually caused the view to load.

For example if your view is LoginScreen your DataContext will be vm:LoginScreenViewModel. you don't need to create a new object of vm:LoginScreenViewModel after LoginScreen is loaded and assign it to view.

查看更多
Lonely孤独者°
3楼-- · 2019-08-14 03:20

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.

查看更多
登录 后发表回答