Passing a complex object to a page while navigating in a WP7 Silverlight application

前端 未结 5 1434
礼貌的吻别
礼貌的吻别 2020-11-30 06:05

I have been using the NavigationService\'s Navigate method to navigate to other pages in my WP7 Silverlight app:

NavigationService.         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 06:32

    There's a very simple solution to tackle this problem. Consider the following example A windows phone app has following two pages, Page1.xaml and Page2.xaml Lets say from Page1.xaml we are navigating to Page2.xaml. The navigation cycle starts, when you call NavigationService.Navigate method

    1. First OnNavigatingFrom Event of Page1 fires
    2. Then Constructor of Page2 fires
    3. Then OnNavigatedFrom event of Page1 fires with the reference of the created page in its EventArgs (e.Content has the created instance of Page2)
    4. Finally OnNavigatedTo Event of Page2 fires

    So we are getting the other page's reference in the page where the navigation starts.

    public class PhoneApplicationBasePage : PhoneApplicationPage
    {
    
    private object navParam = null;
    protected object Parameter{get;private set;}
    //use this function to start the navigation and send the object that you want to pass 
    //to the next page
    protected void Navigate(string url, object paramter = null)
     {    
       navParam = paramter;
       this.NavigationService.Navigate(new Uri(url, UriKind.Relative));
     }
    
    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
    //e.Content has the reference of the next created page
    if (e.Content is PhoneApplicationBasePage )
      {
       PhoneApplicationBasePage  page = e.Content as PhoneApplicationBasePage;
       if (page != null)
       { page.SendParameter(navParam); navParam=null;}
      }
    }
    private void SendParameter(object param)
    {
     if (this.Parameter == null)
      {
       this.Parameter = param;
       this.OnParameterReceived();
      }
    }
    protected virtual void OnParameterReceived()
    {
    //Override this method in you page. and access the **Parameter** property that
    // has the object sent from previous page
    }
    }
    

    So in our Page1.xaml.cs we simply call Navigate("/Page2.xaml",myComplexObject). And in your Page2.xaml.cs we will override OnParameterReceived method

     protected override void OnParameterReceived()
    {
    var myComplexObjext = this.Parameter;
    }
    

    And it is also possible to handle tombstone problems with little more tweaks in PhoneApplicationBasePage

提交回复
热议问题