目前對WP7開發正在研究,對頁面之間參數傳遞進行了一個小總結,有不正確的地方,歡迎大家指正。。
WP7編程採用的技術是Silverlight,頁面之間參數傳遞的方式主要有
- 通過NavigationContext的QueryString方式;
- 通過程式的App類設定全域變數;
- 通過PhoneApplicationService類的State屬性;
- 通過NavigationEventArgs事件類別的Content屬性設定
1.通過NavigationContext的QueryString函數。
首先通過NavigationService類進行設定導航至Page1頁面。
NavigationService.Navigate(new Uri("/Page1.xaml?id=1",UriKind.Relative));
在Page1頁面的PhoneApplicationPage_Loaded方法中可以通過NavigationContext的QueryString方法擷取傳遞的參數值,如下所示。
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e){int id = int.Parse(NavigationContext.QueryString["id"]);}2. 通過程式的App類設定全域變數;
由於App 類繼承自Application類,而通過Application的Current屬性可以擷取到與當前程式關聯的Application類執行個體,然後通過轉換就可以得到App類執行個體,因此,通過在App類中設定全域變數,在程式的其他任何頁面都可以訪問。
public partial class App:Application{ public int ID { get; set;}}假設從頁面Page1中需要把參數傳遞給Page2頁面中,可以先在Page1頁面中先設定;
App app = Application.Current as App;app.Id= 1; //設定傳遞參數;
在Page2頁面擷取設定的參數值;
App app = Application.Current as App;int id = app.ID; //擷取在Page1頁面傳遞參數;
3. 通過PhoneApplicationService類的State屬性;
由於PhoneApplicationService類的State是一個IDictionary類型,因此,可以儲存任何對象,不過這個對象必須是可序列化(serializable)的。
註:PhoneApplicationService類,需要訪問命名空間using Microsoft.Phone.Shell;
在程式中,可以不需要自己建立PhoneApplicationService的執行個體,通過PhoneApplicationService的靜態屬性Current就可以擷取到已有的PhoneApplicationService執行個體
在Page1頁面中設定參數;
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e){ phoneAppService.State["id"] = int.Parse(myTextBox.Text);//擷取Page1頁面的值,進行傳遞; base.OnNavigatedFrom(e);} protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { object myTxt = null; if (phoneAppService.State.ContainsKey("id")) { if (phoneAppService.State.TryGetValue("id", out myTxt)) { myTextBox.Text = myTxt.ToString(); } } base.OnNavigatedTo(e); }在Page2中擷取
protectedoverridevoidOnNavigatedTo(System.Windows.Navigation.NavigationEventArgse){if(PhoneApplicationService.Current.State.ContainsKey("id")){ myTextBlock.Text=PhoneApplicationService.Current.State["id"] as string;}base.OnNavigatedTo(e);}protectedoverridevoidOnNavigatedFrom(System.Windows.Navigation.NavigationEventArgse){PhoneApplicationService.Current.State["id"]=myTextBlock.Text;base.OnNavigatedFrom(e);}4. 通過NavigationEventArgs事件類別的Content屬性設定
在導航至其他頁面函數OnNavigatedFrom中,測試導航的目標頁面是否為自己真正要轉向傳遞參數的頁面,如果是,可以通過NavigationEventArgs事件類別的向目標頁面注入一些"傳遞內容"。
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e){ var targetPage = e.Content as Page2; if (targetPage!=null) { targetPage.ID= 1; //設定參數值 }}在頁面Page2中擷取參數值;
public int ID { get; set; }protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e){ if (param4 != null) { textBlock3.Text = ID.ToString(); //擷取參數值; }}