Local Storage is really helpful to store small amount of data. If you want to save some settings, you can use local storage rather than other storage services. It’s easy to use and flexible of course. So, let’s see how we can use it in our Universal Windows Platform Application.
To start with Local Storage, we will show a really simple example. For basic demonstration purpose, in MainPage.xaml we’ve taken two TextBlock wrapped with a StackPanel. Firstly, TextBlock will show the application starting date and the second one will show time left of a seven days’ time trial.
- <StackPanel>
- <TextBlock Name="textBlock" FontSize="36" Height="50" Width="Auto" Margin="10,10,0,0" Text="Starting date." />
- <TextBlock Name="textBlock1" FontSize="36" Height="50" Width="Auto" Margin="10,10,0,0" Text="Time left." />
- </StackPanel>
Listing: 1
Now, in MainPage.xaml.cs define a OnNavigatedTo method and put the relative code inside the block.
- protectedoverrideasyncvoidOnNavigatedTo(NavigationEventArgs e)
- {
- Windows.Storage.ApplicationDataContainerlocalSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
-
- if ((string) localSettings.Values["IsFirstTimeLaunched"] == "true")
- {
- tex
- tBlock.Text = localSettings.Values["date"].ToString();
- } else
- {
- DateTime start = DateTime.Now;
-
- localSettings.Values["IsFirstTimeLaunched"] = "true";
- localSettings.Values["date"] = start.Date.ToString();
-
- }
-
- DateTime start1 = DateTime.Parse(localSettings.Values["date"].ToString());
- DateTime end = DateTime.Now;
- inttrialPeriod = 7;
-
- if ((end.Date - start1.Date).Days <= trialPeriod)
- {
- textBlock1.Text = "You have " + (trialPeriod - (end.Date - start1.Date).Days).ToString() + " left";
- }
- }
Listing: 2
Firstly, we created ApplicationDataContainer local settings and check a setting “IsFirstTimeLaunched”. If it’s true we show the value otherwise set it “true”, also another setting which is “date”. We set the current date-time to it. So, it will set only once because only the first time the if statement will be false and for the rest of the time it will be always true.
Now, we want to set a seven days’ time period, so that we can count the time elapsed from the start. We create a local variable “end” and “trialPeriod”. We check if the difference between start date and end date is less than seven then we display the time left in the second TextBlock.
If you run the application, it will look like the following,
So, this is a short description of using local storage in your Universal Windows Platform Application. Hope this will help. Happy coding.
Download the source
code.