C# Navigating Between Pages Without losing Data

情到浓时终转凉″ 提交于 2019-12-13 11:10:28

问题


One of my assignments is to pass data to another page which I understand. But how do I get the data to stay when I go back to the Page? Can someone explain how this works.

 public sealed partial class MainPage : Page
    {
       string userName;
       public MainPage()
     {

        this.InitializeComponent();
    }

    private void btnPage2_Click(object sender, RoutedEventArgs e)
    {
        Frame.Navigate(typeof(Page2) ,  userName);
    }

    private void btnName_Click(object sender, RoutedEventArgs e)
    {
        userName = Convert.ToString(txtname.Text);
    }
}

回答1:


I have answered a similar question here. The answer there applies to this problem as well, however in your case you are especially focusing on the data part in question, so here you should pay special attention to the second part of the answer - using a ViewModel that will outlive the page itself would be the most beneficial solution. However using NavigationCacheMode will be sufficient as well, as the page class itself along with its fields will be preserved.

There is a third option available here, which is using static for the field you want to keep, or creating a static or singleton class that will hold the data. This however comes with a disadvantage when compared to the ViewModel solution as it does not easily allow having a single page multiple times in the navigation stack with different state data.



来源:https://stackoverflow.com/questions/49112925/c-sharp-navigating-between-pages-without-losing-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!