Search code examples
c#visual-studio-2013windows-phone-8-emulator

Passing data between multiple forms


I am creating a WindowsPhone app and (at the moment) I have three pages. Page1, page2 and page3. Page1 has two (2) textboxes that accepts the fist and last name, txtFN and txtLN and a button. The button takes you to the form2, that asks you the nickname. That has one textbox and a button. When the user clicks the button, it takes him the form3 that has a textblock. The nickname the user inputs in form2, displays in form3, on the textblock. I have gotten that part correct. Now, I am trying to do this: if the user does not input anything in the nick name section, I would like to show the first name in form three. Here's my code for form2->form3 event:

in form2:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Frame.Navigate(typeof(Page4_phone_Number_extraction), "Alright " + Texbox_nickname_extraction.Text + "!");
}

in form3,

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    Textblock_nickname_display.Text = e.Parameter.ToString();
}

And this works like a charm..

Again, for the life of me, i can't think of how to have the first name show up in form3, if there is no user input.


Solution

  • One option would be to store the data in a local app settings like:

    Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    localSettings.Values["FirstName"] = txtFN.txt;
    

    in page 1.

    You can then extract it in page 3 as:

    Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    Textblock_nickname_display.Text=localSettings.Values["FirstName"].ToString();
    

    You can also use OnNavigatedFrom() to achieve the same functionality, but it involves more work:

    In Page1:

    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        Page2 destinationPage = e.Content as Page2;
        if (destinationPage != null)
        {
            destinationPage.FirstName = txtFN.Text;
        }
    }
    

    Make sure to have a string FirstName {get;set;} in Page2. Now use the same method to send the variable to Page3 too. You can then use the FirstName variable in Page3.

    Needless to say, the first method is simpler.