开发者

WP7 running method on exit

I have a page in my WP7 which contains some text boxes. When pressing the back key this method is run to save the contents:

 protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
    {
        var settings = IsolatedStorageSettings.ApplicationSettings;

        settings["remZone"] = txtBoxZone.Text;
        settings["remSpace"] = txtBoxSpace.Text;
    }

The problem is some users would not press the back button, but would press the home button to exit the app, so the contents are not saved.

I think there are two avenues round this if possible: 1. Is there a function that would run this method when the home button is pressed, like the onBackKeyPress. 2. Is there a simple way to save the contents of the text box as the user is entering it?

Thanks.

EDIT:

solution was this:

   protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
     {
         var settings = IsolatedStorageSettings.ApplicationSettings;

         settings["remZone"] = 开发者_Go百科txtBoxZone.Text;
         settings["remSpace"] = txtBoxSpace.Text;
     }


The simplest solution to your problem would be overriding Page.OnNavigatingFrom method.

more here


Backpress is not the only event that you receive, there's also an App.Deactivated event, that is guaranteed to be called whenever your app goes off the screen in whatever way.

In your Page (either the .ctor or Loaded eventhandler), attach a handler to that event, and in that handler collect everything you must store in case of being closed. This is the simpliest way to be sure that it will not evaporate. Just remember to unlink that handler upon Page.Unloaded, or else you will greatly leak the memory/resources!!

BTW. The code

var settings = IsolatedStorageSettings.ApplicationSettings;

settings["remZone"] = txtBoxZone.Text;
settings["remSpace"] = txtBoxSpace.Text;

is not sufficient in some cases. If you really need to be sure that your settings are persisted, you must manually call Save() after the changes:

var settings = IsolatedStorageSettings.ApplicationSettings;

settings["remZone"] = txtBoxZone.Text;
settings["remSpace"] = txtBoxSpace.Text;

settings.Save(); // think about it, you may want it!

this is because the Settings are stored on some specific occasions, like application quit, tombstoning etc. I don't remember about them being saved upon deactivation, so just pressing Back may not save them to the ISO. What's more, if you set them and the App crashes - for example due to unhandled exception - or if the battery/power goes down, or the user simply turns off the phone - they will not be stored!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜