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);
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.