简体   繁体   中英

How can I prevent my ViewModel from being instantiated twice when navigating between views?

I have used this blog and this SO question to setup MVVM in my WPF app. My issue is that my viewmodels are being instantiated twice. And I have code in their constructors that needs to only run once.

I have a content control on my MainWindow.xaml:

<ContentControl Content="{Binding CurrentViewModel, UpdateSourceTrigger=PropertyChanged}" />

On my MainWindow ViewModel I load other viewmodels using MVVM Light messenger service:

Messenger.Default.Register<BaseViewModel>(this, ChangeViewModel);
private void ChangeViewModel(BaseViewModel viewModel)
{
    CurrentViewModel = viewModel;
}

Then on other views I use the messenger service to tell the MainWindow ViewModel to load another ViewModel:

Messenger.Default.Send((BaseViewModel)new AuthViewModel());

The problem is that when this new View is loaded I set the DataContext in the code behind:

    public AuthView()
    {
        InitializeComponent();
        DataContext = new AuthViewModel();
    }

This results in the constructor for AuthViewModel being run twice. What is the proper way to do this?

Change this:

private void ChangeViewModel(BaseViewModel viewModel)
{
    CurrentViewModel = viewModel;
}

TO

private void ChangeViewModel(BaseViewModel viewModel)
    {
var issame = this.CurrentViewModel == null ? false : viewModel.GetType().Equals(this.CurrentViewModel.GetType());
                if (issame)
                    return;
else
CurrentViewModel = viewModel;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM