首页 文章

通过多个页面传递参数

提问于
浏览
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 回答

  • 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));
    }
    

相关问题