2017-03-04 103 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