【发布时间】:2010-07-22 17:21:08
【问题描述】:
有没有办法使用 MVVM Light 来处理关闭、停用、激活等应用程序事件?
【问题讨论】:
标签: mvvm windows-phone-7 mvvm-light
有没有办法使用 MVVM Light 来处理关闭、停用、激活等应用程序事件?
【问题讨论】:
标签: mvvm windows-phone-7 mvvm-light
感谢 Matt Casto 将我引向正确的方向。
这是工作代码:
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));
}
视图模型:
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;
}
});
【讨论】:
您可以做的一件事是在 App.xaml.cs 中处理这些事件,并让它们使用默认的 Messenger 实例发送消息。然后让任何视图模型注册以接收消息。如果您需要取消事件,请使用带有回调的消息来告诉应用程序取消。
【讨论】: