WPF C# - Textblock inputs not saving on Navigation to new page?

25 views Asked by At

I'm currently having trouble with page navigation in WPF, I currently have a MainWindow with a sidebar, and a Frame in the middle of the window to display new pages. The sidebar navigation seems to work fine, but the issue is whenever I navigate to a new page and back, it doesn't save any of the information that was filled out in any of the textblocks.

I was going to use a .settings file for storing this, but I only want the user inputs to be stored at runtime, once the application is closed I don't need the information to be saved for the next launch. I don't see any errors / warnings being thrown on my end.

  • I have tried using KeepAlive=true for each page with no luck, I was thinking the issue was that when each button is pressed I am "recreating" the page instead of moving back to it, so it is erasing the inputs(?)

(If it helps, I am using .NET 6.0)

Thanks in advance for the help, apologies if the question is basic, I am still learning.

C#:

  public partial class MainWindow : Window
  {


      public MainWindow()
      {
          InitializeComponent();
          MainFrame.Navigate(new Uri("P1Home.xaml", UriKind.RelativeOrAbsolute));
      }

      private void BtnHomePage_Click(object sender, RoutedEventArgs e)
      {
          MainFrame.Navigate(new Uri("P1Home.xaml", UriKind.RelativeOrAbsolute));
      }

      private void BtnDependencies_Click(object sender, RoutedEventArgs e)
      {
          MainFrame.Navigate(new Uri("P4Dependencies.xaml", UriKind.RelativeOrAbsolute));
      }

      private void BtnFinish_Click(object sender, RoutedEventArgs e)
      {
          MainFrame.Navigate(new Uri("P5Final.xaml", UriKind.RelativeOrAbsolute));
      }
1

There are 1 answers

0
zasdev On

After playing around for a while, I was able to come up with a solution that seems to work well for my application:

App.xaml.cs:

// Defining static instances of each page

public static class PageInstances
    {
        public static PageOne PageOneInstance { get; } = new PageOne();
        public static PageTwo PageTwoInstance { get; } = new PageTwo();
        // Define other Pages here
    }

MainWindow.xaml.cs:

// Navigation logic via buttons (located in a sidebar)

   private void BtnPageOne_Click(object sender, RoutedEventArgs e)
    {
        MyFrame.NavigationService.Navigate(PageInstances.PageOneInstance);
    }

    private void BtnPageTwo_Click(object sender, RoutedEventArgs e)
    {
        MyFrame.NavigationService.Navigate(PageInstances.PageTwoInstance);
    }

Explaination: By generating static instances of each of my pages when the application first starts, I am able to simply navigate between the static instances of each page, that are saved upon each navigation.

Hopefully this helps somebody out there, thanks for reading.