views:

407

answers:

1

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?

+2  A: 

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.

Matt Hamilton
Solved! Thanks! Amazing. Even the book WPF Unleashed says the same as MSDN.
Eduardo Molteni