2010-11-15 22 views
0

我遵循恢復我的持久性和非持久性狀態以及對象在重新啓動邏輯刪除應用程序時的一般最佳做法原則。這些都是在本很不錯的Microsoft文章Windows Phone 7:確定在Application_Activated事件期間正在激活哪個頁面

here

樣品僅顯示應用的主要頁面的簡單的重新啓動中找到。然而,因爲我的應用程序有多個頁面(其中任何一個都可能是墓碑並因此重新激活),並且每個頁面都綁定到不同的ViewModel對象。我想知道如何確定哪個頁面最終將被激活,以便我可以選擇性地反序列化併爲該頁面恢復正確的ViewModel對象。

或者是恢復所有ViewModels的最佳做法還是有其他設計模式?

回答

1

我已經實施了最好描述爲一個簡單的模式 -

  1. 在應用程序的啓動和關閉事件,我將消息發送給訂閱頁面。
  2. 預訂消息的頁面執行數據的序列化/反序列化。

我正在使用Laurent Bugnion's excellent MVVMLight library for Windows Phone 7。這是圖示出消息廣播一些示例代碼 - 在一個視圖模型類的構造函數

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

,我設置了訂閱的通知消息 -

// 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

+0

謝謝。這看起來不錯。我也在使用MVVM Light。我會在今天早上發佈這個模式並讓你知道。我對MVVM相當陌生,我還沒有使用消息框架! – NER1808 2010-11-16 09:32:38

相關問題