Search code examples
vb.netwindows-phone-8navigationservice

Storing variables between pages VB WP8


I have an app that records time as you press a button. So leave office, arrive site, leave site and arrive office. I have created a button that allows the user to input what parts have been used on the job. This takes you to another screen where input takes place. I can pass these variables back to the main page but because I'm using:

NavigationService.Navigate(New Uri("/MainPage.xaml?msg=" & textBox1.Text, UriKind.Relative))

It resets the data that was in main page.

When I use the NavigationService.GoBack(), the data remains.

Is there a way to keep that data when I am navigating away from the main page?


Solution

  • Yes, just keep the data/datacontext/object on App level.

    So for example, use an object in App.xaml.vb

    Public Shared Property MyBook() As Book
    Get
        Return m_MyBook
    End Get
    Set
        m_MyBook = Value
    End Set
    End Property
    Private Shared m_MyBook As Book
    

    And in the OnNavigatingFrom event on your page (or even before, wherever you like), save that data

    Protected Overrides Sub OnNavigatingFrom(ByVal e As System.Windows.Navigation.NavigatingCancelEventArgs)
        App.MyBook = currentBook
    End Sub
    

    When navigating back to that page, just check if the App.MyBook is null, if it's not, it means you've cached something before navigating, so just read it and set the current datacontext to it (or however you set your data on the page)

    Protected Overrides Sub OnNavigatedTo(ByVal e As System.Windows.Navigation.NavigationEventArgs)
        If (App.MyBook Is Nothing) Then
    
        Else
            currentBook = App.MyBook
        End If
    End Sub
    

    (since you shared no relevant code, my implementation is rather abstract, but the main point is - keep it in the App.xaml.cs and save/load it when you need it)