問題描述
我一直在使用 NavigationService
的 Navigate
方法導航到我的 WP7 Silverlight 應用程序中的其他頁面:
I have been using the NavigationService
's Navigate
method to navigate to other pages in my WP7 Silverlight app:
NavigationService.Navigate(new Uri("/Somepage.xaml?val=dreas", UriKind.Relative));
從Somepage.xaml
,然后我檢索查詢字符串參數如下:
From Somepage.xaml
, I then retrieve the query string parameters as follows:
string val;
NavigationContext.QueryString.TryGetValue("val", out val);
<小時>
我現在需要一種使用類似方式傳遞復雜對象的方法.每次我需要將對象傳遞到新頁面時,如何不必序列化對象?
I now need a way to pass a complex object using a similar manner. How can I do this without having to serialize the object every time I need to pass it to a new page?
推薦答案
這是一個極其復雜的問題,這里沒有簡單的解決方案.沒有任何神奇的 API 可以適用于任何應用來解決這個問題.
This is an extremely complex problem, and there is no simple solution here. There is no magic API that would just work for any app to solve this problem.
傳遞導航數據的核心問題是墓碑.默認情況下唯一被墓碑化的數據是導航 URI.因此,如果您使用的是 QueryString 參數,它將被墓碑和您的代碼自動拾取.但是,任何時候您手動傳遞對象的實例時,您都必須自己手動為該實例執行墓碑.
The core problem with passing navigation data is Tombstoning. The only piece of data that is tombstoned by default is the Navigation URI. so if you're using a QueryString parameter, it'll get picked up automatically by tombstoning and your code. Any time you'll manually pass a instance of an object though, you'll have to manually do tombstoning for that instance yourself.
因此,如果您導航到/CowDetails.xaml?ID=1",您的頁面可能只需選擇 ID Querystring 參數即可擁有完美的墓碑.但是,如果您以某種方式為 CowDetails 頁面提供new Cow() { ID = 1}",則必須確保自己墓碑化并僵尸化此值.
So, if you navigate to "/CowDetails.xaml?ID=1" your page will probably have perfect tombstoning just by picking up on the ID Querystring Parameter. However, if you somehow provide CowDetails page with a "new Cow() { ID = 1}" you'll have to make sure to tombstone and zombificate this value yourself.
還有時間問題.在調用 NavigationService.Navigate 時,您正在導航的頁面還沒有實際實例.因此,即使您正在導航到 FooPage 并準備好 FooData,也無法立即將 FooPage 連接到 FooData.您必須等到 PhoneApplicationFrame.Navigated 事件觸發后才能為 FooPage 提供 FooData.
Also, there's the issue of timing. While calling NavigationService.Navigate, the page you're navigating too doesn't have an actual instance yet. So even though you're navigating to FooPage and have the FooData ready, there's no way to immediately connect FooPage to FooData. You'll have to wait until the PhoneApplicationFrame.Navigated event has fired in order to provide FooPage with FooData.
我通常處理這個問題的方式是:
The way I normally deal with this is problem:
- 擁有一個帶有 Object 類型 Data 屬性的 BasePage
- 讓 NavigationHelper 獲取頁面 URI 和數據:NavigationHelper.Navigate("foo.xaml", fooData)
- 讓 NavigationHelper 注冊到 PhoneApplicationFrame.Navigated 事件,如果它是foo.xaml",則將 BasePage.Data 設置為 FooData.
- 讓 BasePage 使用 JSON.Net 墓碑和僵尸化 BasePage.Data.
- 在 BasePage 上,我有一個 OnDataSet 虛擬方法,一旦通過 Zombification 或 Navigation 填充 Data 屬性,就會調用該方法.在這種方法中,與業務數據有關的一切都會發生.
這篇關于在 WP7 Silverlight 應用程序中導航時將復雜對象傳遞到頁面的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!