私は次のように最もよく説明される単純なパターンを実装しました-
- アプリケーションのアクティブ化および非アクティブ化イベントで、サブスクライブしているページにメッセージを送信します。
- メッセージをサブスクライブするページは、データのシリアル化/逆シリアル化を実行します。
私は、LaurentBugnionの優れたMVVMLightライブラリをWindowsPhone7用に使用しています。メッセージブロードキャストを示すサンプルコードを次に示します-
// Ensure that application state is restored appropriately
private void Application_Activated(object sender, ActivatedEventArgs e)
{
Messenger.Default.Send(new NotificationMessage<AppEvent>(AppEvent.Activated, string.Empty));
}
// Ensure that required application state is persisted here.
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
Messenger.Default.Send(new NotificationMessage<AppEvent>(AppEvent.Deactivated, string.Empty));
}
ViewModelクラスのコンストラクター内で、通知メッセージのサブスクリプションを設定します-
// Register for application event notifications
Messenger.Default.Register<NotificationMessage<AppEvent>>(this, n =>
{
switch (n.Content)
{
case AppEvent.Deactivated:
// Save state here
break;
case AppEvent.Activate:
// Restore state here
break;
}
}
この戦略では、ViewModelにバインドされているページに関連するすべてのデータが適切に保存および復元されることがわかりました。
HTH、indyfromoz