ArgumentNullException on changing frame

2019-04-25 18:41发布

问题:

So I'm trying to change frames in a windows 8 app. I tried following the tutorial at this page, but I keep getting the same error.

I'm getting an ArgumentNullException on the line:

frameState[_pageKey] = pageState;

in the LayoutAwarePage.cs class, in the OnNavigatedFrom method.

Now I'm not sure why I get this error, because I feel that there is nothing that could cause it in my code. My button onclick function has this code:

DateTime chosenDateTime = new DateTime(year, month, day, hours, minutes, seconds);
this.Frame.Navigate(typeof(MainPage), chosenDateTime.ToString());

And the OnNavigatedTo method in my MainPage looks like this:

protected override void OnNavigatedTo(NavigationEventArgs e) {
   string parameter = (string)e.Parameter;
   if (parameter != "") {
       Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
       roamingSettings.Values["chosenDateTime"] = parameter;
       chosenDateTime = Convert.ToDateTime(e.Parameter);
   } else {
       Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
       if (roamingSettings.Values.ContainsKey("chosenDateTime")) {
           chosenDateTime = Convert.ToDateTime(roamingSettings.Values["chosenDateTime"].ToString());
       }
       if (roamingSettings.Values.ContainsKey("headline")) {
           chosenDateTextBlock.Text = roamingSettings.Values["headline"].ToString();
       }
   }
   SetTime();
}

Can anyone give me some information as to how I can solve this?

Thanks.

回答1:

Alright, so I found the answer to my own question!

On both pages I refer to and from I had to have implemented at least the minimal implementation of the 2 methods:

protected override void OnNavigatedTo(NavigationEventArgs e) {
    base.OnNavigatedTo(e);
}

protected override void OnNavigatedFrom(NavigationEventArgs e) {
    base.OnNavigatedFrom(e);
}

And the

base.OnNavigatedFrom(e);
base.OnNavigatedTo(e);

were very important to have in the methods.



回答2:

One other situation that may trigger this problem is if the page is no longer attached to any frame (e.g. it's still in memory because of event handlers or other references but its frame has already been navigated away from the page).

This is very easy to do accidentally if you call Frame.Navigate() in an event handler that may be triggered multiple times or attached to the event multiple times (the first invocation will work, but the second one will be called after the page no longer has any frame).