Search code examples
wpfxamlmvvmviewmodellight

MVVM Light with WPF ViewModel Navigation Actions


Good Day!

I am using MVVM Light on a WPF app. I have a single page and I'm using User Controls to provide views with their own respective ViewModels. I'm using the ViewModelLocator to have those wired up. I've figured out how to navigate by binding the ContentControl's Content to an observable property that gets set. Here is a snipet of the XAML:

<ContentControl Content="{Binding CurrentViewModel}" Grid.Row="1" />

The MainViewModel creates references to my two different ViewModels:

private ViewModelBase _currentViewModel;
private readonly static LogInViewModel _loginViewModel = new LogInViewModel();
private readonly static ClockEventViewModel _clockEventViewModel = new ClockEventViewModel();

In my constructor I register some Actions from the other ViewModels:

_loginViewModel.AllowClockEvent += ExecuteClockEventViewCommand;
_clockEventViewModel.ReturnToLogin += ExecuteLoginViewCommand;

They are implemented in each ViewModel like this:

public Action ReturnToLogin = delegate { };

Finally in those methods I set the CurrentViewModel to the different ViewModel. For example:

CurrentViewModel = _clockEventViewModel;

This works fine, but what I cannot do is, upon the other viewmodel becoming the current one, I'd like to capture that and do some initial work. Kind of like a NavigateTo event. I'm sure there is probably an easy way, but I've looked at the ViewModelBase and I see no method to override giving me this capability.

Who has already done this? If there is a better way then the approach I've made, please let me know.


Solution

  • What I end up doing is calling the method I'm needing through the exposed _clockEventViewModel. It was actually easier than I thought.