WPF NavigationService creating new Pages each time

2.3k Views Asked by At

I am using the WPF NavigationService to navigate from one Page to another in my application like so:

    private void Image_Forward_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (YesNo.Choice == "yes")
        {
            NavigationService.Navigate(new PageQuestion2Yes());
        }
        else if (YesNo.Choice == "no")
        {
            NavigationService.Navigate(new PageQuestion2No());
        }
    }

I have found that if I navigate to a page more than once then each time a new Page object is getting created. ( I noticed this my adding a constructor in my pages and displaying a messagebox and I found that when the main application exits all the Pages get destroyed)

How can I use NavigationService so that there is only ever one Page created during the lifetime of my application??

1

There are 1 best solutions below

1
On

Quite evident from your code that you want always new object of Page after navigation:

// Calling constructor manually.
NavigationService.Navigate(new PageQuestion2Yes());

Instead store object in class level field and always navigate to that object:

private PageQuestion2Yes yesObject = new PageQuestion2Yes();

Now in method pass that object always on navigation:

NavigationService.Navigate(yesObject);