In my last post I gave an introduction to the Windows Phone 7: Application Lifecyle. This one is a bit about binding your user interface in order to store persistent and transient data on the device.

So Windows Phone 7 isn't just a phone, it's a pretty awesome gadget and work tool. [I want one - accepting donations ;)]. Users will, no doubt, be making heavy use of the applications available on the market place daily. But there will be many distractions and needs to exit your application. Although you can override the back button press you can't stop this from happening so if you want to keep data you'll need a place to store it.

Thankfully, WP7 lets you do this easily with the methods fired on application events. It just requires a little know-how and you'll be away persisting and using data in your application.

Firstly a bit about how to link your interface to a class using your data. You'll need a class for the data items on the screen you wish to save if you're saving user inputs. Here's an example from a basic application:


From this you can see that the private members NotifyPropertyChanged(Name) any time they are changed. This is a private function, which we've made that notifies your application that a field has been updated. For your application to incorporate this the XAML for the text attribute of your input field should be bound to this object.

To do this open up App.xaml.cs and instantiate your class within the Application_Launching method. Then set to be your data context:
RootFrame.DataContext = yourClass;
Then in your page's XAML file under the Text attribute add {Binding Persistant, Mode TwoWay}. Now when you run your application your class is bound to the user interface. Ready to start saving. Being TwoWay allows you to update the field programatically as well as the user having being allowed to do so.