Reputation: 23
I am using a <Frame ..../> in the MainWindow.xaml to switch between two pages. The problem is that, when I return to a page all data (like textBox.Text and so on) are erased. How can I switch between the pages and keep their information all?
Loading a page is done by ClickHandler of a button in the MainWindow.xaml.cs. below is the code of ClickHandler.
private void ClickHandlerButton1(object sender, RoutedEventArgs e)
{
mainFrame.Content = new page1();
}
private void ClickHandlerButton2(object sender, RoutedEventArgs e)
{
mainFrame.Content = new page2();
}
I believe, once I click the button it creates a new page(), so I actually don't return to the same page() but go to a new page(). Therefore, there are no data to show back. However, I don't know how to get rid of this issue.
Thank you in advance.
Upvotes: 2
Views: 1281
Reputation: 321
You are instantiating a new page and storing its reference in the Content
property that was referencing the previous page.
There are multiple ways to achieve what you need:
One would be to share the viewmodel (the page where the mainFrame is has a viewmodel shared with page 1 and page 2).
Other way would be to (depending on how is your layout) to use navigation pages, carouselviews or another control that behaves like you expect. This way you keep alive the references of the views.
The third one is what Taehyung Kim said. Another way to keep the references alive is to have 2 variables. Every variable referencing an instance, in your case, page1 and page2. Then everytime that the page has to be loaded, you don't create a new instance, instead, you reuse the stored reference.
Fourth would be using datacontext of the page (for the bindings).
Fifth would be passing data at the constructor of the page (it is less performant than the second way).
Here is a link to microsoft docs that has some parts on passing data between navigations hierarchical navigation
Upvotes: 3
Reputation: 640
You just use cache.
Example.
Page page1 = new Page();
Page page2 = new Page();
private void ClickHandlerButton1(object sender, RoutedEventArgs e)
{
mainFrame.Content = page1;
}
private void ClickHandlerButton2(object sender, RoutedEventArgs e)
{
mainFrame.Content = page2;
}
Upvotes: 4