Search code examples
c#wpfnavigation

WPF event if page is navigated to


Description

In my WPF C# project I have multiple pages that are navigated to using the navigation service. Some of them are not always new instances, but rather saved to then be loaded again on the next navigation to it.

This leaves me with the problem that the variables inside do not reset when the page is loaded again.

What I have tried

In my first WPF project I just grabbed the Instance before navigating to it and reset all of the required variables manually. This is probably the simplest but most redundant solution, since I have to add this functionality before each navigation.

Now I tried just detecting whether a page is navigated to. With that I could just add a method to reset all of the variables that is automatically called if the respective page is navigated to.

I found this solution on Stackoverflow. Though when trying to implement into my Settings page, it leaves me with the error:

"Settings.OnNavigatedTo(NavigationEventArgs)": No suitable method found to override

Further research lead me to this solution. When implementing this line into my MainWindow.cs:

NavFrame.Navigate += OnNavigatedTo;

the following error occurs:

The Name "OnNavigatedTo" does not exist in the current context

Question

What is either a fix for my chosen approch OR what is another approach to detect such an event for my kind of purpose?


Solution

  • If I understand your issue correctly, you should be able to handle the Loaded event for the Page to detect when it is being navigated to in WPF:

    public partial class Page1 : Page
    {
        public Page1()
        {
            InitializeComponent();
            Loaded += OnLoaded;
        }
    
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            // reset state here...
        }
    }