2017-03-04 182 views
0

我在Xamarin可移植類庫(目標平臺UWP)中創建了一個應用程序,用戶在每個頁面中填充幾個TextBox。我需要將這些信息保存在最後一頁的xml文件中(點擊按鈕),因此我需要將信息通過每個頁面傳遞給最後一頁。我怎麼做?通過多個頁面傳遞參數

這裏我序列化類:

namespace myProject 
{ 
[XmlRoot("MyRootElement")] 
     public class MyRootElement 
     { 
      [XmlAttribute("MyAttribute1")] //name of the xml element 
      public string MyAttribute1  //name of a textboxt e.g. 
      { 
       get; 
       set; 
      } 
      [XmlAttribute("MyAttribute2")] 
      public string MyAttribute2 
      { 
       get; 
       set; 
      } 
      [XmlElement("MyElement1")] 
      public string MyElement1 
      { 
       get; 
       set; 
      } 
} 

這是我的第一頁:

namespace myProject 
{ 
    public partial class FirstPage : ContentPage 
    { 
     public FirstPage() 
     { 
      InitializeComponent(); 
     } 
     async void Continue_Clicked(object sender, EventArgs e) 
     { 
      MyRootElement mre = new MyRootElement 
      { 
       MyAttribute1 = editor1.Text, 
       MyAttribute2 = editor2.Text, 
       MyElement1 = editor3.Text 
      }; 
      await Navigation.PushAsync(new SecondPage(mre)); 
     } 
    } 
} 

第二頁看起來像這樣由一個非常有用的用戶建議在這裏(我聽錯了,我猜的):

namespace myProject 
{ 
    public partial class SecondPage : ContentPage 
    { 

     public MyRootElement mre { get; set; } 

     public SecondPage(MyRootElement mre) 
     { 
      this.mre = mre; 
      InitializeComponent(); 
     } 

     async void Continue2_Clicked(object sender, EventArgs e) 
     { 
      MyRootElement mre = new MyRootElement 
      { 
       someOtherElement = editorOnNextPage.Text 
      }; 
      await Navigation.PushAsync(new SecondPage(mre)); 
     } 
    } 
} 

在文件被創建的最後一頁:

namespace myProject 
{ 
    public partial class LastPage : ContentPage 
    { 
     private MyRootElement mre { get; set; } 

     public LastPage(MyRootElement mre) 
     { 
      this.mre = mre; 
      InitializeComponent(); 
     } 

     private async void CreateandSend_Clicked(object sender, EventArgs e) 
     { 
      var s = await DependencyService.Get<IFileHelper>().MakeFileStream(); //stream from UWP using dependencyservice 

      using (StreamWriter sw = new StreamWriter(s, Encoding.UTF8)) 
      { 
       XmlSerializer serializer = new XmlSerializer(typeof(MyRootElement)); 
       serializer.Serialize(sw, mre); 
      } 
     } 
    } 
} 

如果您需要更多內容才能回答我的問題,請讓我知道。

回答

1

您只需在第一頁上創建一次MyRootElement實例。之後,繼續使用後續頁面的相同實例。

async void Continue2_Clicked(object sender, EventArgs e) 
{ 
    // use the same copy of mre you passed via the construt 
    this.mre.someOtherElement = editorOnNextPage.Text 

    await Navigation.PushAsync(new SecondPage(mre)); 
} 
+0

它的工作!先生,謝謝你! – RoloffM