Tips, tricks, and guides for developing on modern Windows platforms
This is a simple tip that works with both Windows Phone and Windows 8. Dealing with isolated storage settings can be a bit cumbersome. Wouldn’t it be easier if you could treat a stored setting or value like a regular variable?
This tip shows you how to do that using Visual Basic.net in Windows 8 and Windows Phone apps.
Instead of directly interacting with a setting stored in your app’s isolated storage, this technique lets you treat your settings value like any other variable (or more specifically a property).
Compare the following code for changing the value of the stored (i.e. persistent in isolated storage) NumberOfLives:
NumberOfLives = x + 1
As compared to:
ApplicationData.Current.RoamingSettings.Values("settingname") = "hello world"
Note: you must also make sure the isolated storage setting is created before trying to write to it, or you’ll get an error.
Reading the value:
X = NumberOfLives
X = ApplicationData.Current.RoamingSettings.Values("settingname")
As you can see, encapsulating the isolated storage value as a property makes the rest of your code easier to write, read, and maintain.
The beauty of this technique is that it is very flexible. Properties give you the opportunity to create variables that contain their own internal logic. In this example we’ll just create a very simple property that reads and writes a specified isolated storage value.
Private _numberOfLives as Integer
Public Property NumberOfLives as Integer
_numberOfLives = value
ApplicationData.Current.RoamingSettings.Values("NumberOfLivesStored") = _numberOfLives.ToString
A detailed look at the code
Let’s look at the code line by line so you can understand exactly what is happening here.
If you add the code above into your project it will most likely fail! The code is correct, but you’re missing something. To work with isolated storage settings you need to create them before reading or writing their values.
There are two obvious ways to do this. The most foolproof way is to always check if the property exists before reading or writing to it. You could alternatively implement logic in your project that creates all isolated storage properties before they are ever used.
In a future post I’ll put up a full implementation of settings that incorporates logic to check if isolated storage settings exist before attempting to read or write them.
Once you implemented properties in this way they can be used just like regular variables…except their values will persist when the app is closed! This is ideal for storing application settings that need to accessed by your code a lot.