Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep page with full state in navigation wpf app

I'm building a WPF app using pages and the navigation service.
One of the pages take an object as a constructor

Sub New(ByVal o As Object)
    ' This call is required by the Windows Form Designer.
    InitializeComponent()

    ....

So, to navigate to it I do

    Dim MyPage As New Page1(MyObject)
    MyBase.NavigationService.Navigate(MyPage)

The problem occurs when I'm editing something in the page, and go back, and the forward to MyPage i get the following error:

 Cannot create object of type 'Page1'. CreateInstance failed, which can be 
 caused by not having a public default constructor for 'Page1'.  

What am I doing wrong?

like image 783
Eduardo Molteni Avatar asked Mar 01 '23 18:03

Eduardo Molteni


1 Answers

You need to tell the host application that the page should persist in memory, rather than being "unloaded" every time you navigate away and "reloaded" when you come back to it. That turns out to be pretty easy: Just add the KeepAlive attribute to your page declaration:

<Page x:Class="..." KeepAlive="True">

Interestingly, the MSDN documentation says this:

Pages that are instantiated and navigated to using only code (for example, calling Navigate), are automatically kept alive.

I've not found that to be the case, and from your question it seems you're not finding it that way either.

like image 130
Matt Hamilton Avatar answered Mar 04 '23 10:03

Matt Hamilton