开发者

MVVM Light - WP7 Page/Application Events

开发者 https://www.devze.com 2023-01-08 23:45 出处:网络
Is there a way to use MVVM Light to handle application events li开发者_如何学Cke Closed, Deactivated, Activated, etc?Thanks to Matt Casto for sending me in the right direction.

Is there a way to use MVVM Light to handle application events li开发者_如何学Cke Closed, Deactivated, Activated, etc?


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;
    }
});


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号