Reputation: 14383
Is there a way to use MVVM Light to handle application events like Closed, Deactivated, Activated, etc?
Upvotes: 3
Views: 995
Reputation: 14383
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;
}
});
Upvotes: 5
Reputation: 2170
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.
Upvotes: 4