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?