我正在編寫一個WP7應用程序,該應用程序在其頁面的OnNavigatedTo()覆蓋處理程序中的主UI線程上恢復其狀態。在這個處理程序中,它將頁面的列表框ItemsSource屬性設置爲反序列化的ObservableCollection數據項。反序列化來自獨立存儲,速度很快,不會掛起線程。什麼時候應該設置ListBox的ItemsSource屬性?
但是,當頁面出現時,列表框爲空。在設置斷點並檢查頁面狀態時,Items屬性正確填充且非空。
如果我遲疑ItemsSource屬性的設置,像這樣:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
int delayMs = 100; // Why 100 ?
runDelayedDispatch(Deployment.Current.Dispatcher,
delayMs, delegate()
{
deserializeFromStorageAndSetItemsSource();
});
}
...
// Does a BeginInvoke() after the specified delay.
public static void runDelayedDispatch(Dispatcher dispatcher,
int delayInMilliseconds, Action action)
{
Action dispatcherAction = delegate()
{
dispatcher.BeginInvoke(action);
};
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, e) => Thread.Sleep(delayInMilliseconds);
worker.RunWorkerCompleted += (s, e) => dispatcherAction.Invoke();
worker.RunWorkerAsync();
}
然後一切工作正常。
我在做什麼錯?我應該從不同的處理程序或稍後在應用程序生命週期中的隔離存儲中讀取數據嗎?
文章有關的應用程序生命週期還沒有有何啓示這個:(
http://msdn.microsoft.com/en-us/library/system.windows.controls.page.onnavigatedto(v=vs.95).aspx http://msdn.microsoft.com/en-us/library/cc838245(v=vs.95).aspx http://windowsphonegeek.com/articles/WP7-Application-Lifecycle-and-Tombstoning http://visualstudiomagazine.com/articles/2011/06/01/pcmob_app-lifecycle.aspx
謝謝!
runDelayedDispatch是一個很酷的功能 - 不過考慮將delayInMilliseconds改爲TimeSpan。 – 2012-01-03 06:17:10
有什麼好處? :) – swinefeaster 2012-01-03 06:28:24
順便說一句,我從這裏得到它:http://stackoverflow.com/questions/4726239/easy-way-to-excecute-method-after-a-given-delay – swinefeaster 2012-01-03 06:30:32