views:

237

answers:

2

Is there a way to use MVVM Light to handle application events like Closed, Deactivated, Activated, etc?

+4  A: 

One thing you could do is handle these events in the App.xaml.cs and have them send a message using the default Messenger instance. Then just have any view models register to receive the message. If you need to cancel the event, use the message with a callback telling the application to cancel.

Matt Casto
I like it. Thanks!
chief7
+4  A: 

Thanks to Matt Casto for sending me in the right direction.

Here is the working code:

App.xaml.cs:

    private void Application_Activated(object sender, ActivatedEventArgs e)
    {
        Messenger.Default.Send(new NotificationMessage<AppEvents>(AppEvents.Activated, string.Empty));
    }
    private void Application_Deactivated(object sender, DeactivatedEventArgs e)
    {
        Messenger.Default.Send(new NotificationMessage<AppEvents>(AppEvents.Deactivated, string.Empty));
    }
    private void Application_Closing(object sender, ClosingEventArgs e)
    {
        Messenger.Default.Send(new NotificationMessage<AppEvents>(AppEvents.Closing, string.Empty));
    }

ViewModel:

Messenger.Default.Register<NotificationMessage<AppEvents>>(this, n =>
{
    switch (n.Content)
    {
        case AppEvents.Deactivated:
            _sessionPersister.Persist(this);
            break;
        case AppEvents.Activated:
            var model = _sessionPersister.Get<TrackViewModel>();                
            break;
    }
});
chief7