Handling Application Settings (Windows 8 App settings change notification)
I received two a great question last night at an ACM event at Illinois Institute of Technology. We were using the ApplicationDataContainerSettings via ApplicationData.Current.RoamingSettings.Values which is a Map type collection (.e.g.; it holds key and value pairs). We were specifically using it to store application configuration information. For our app we were saving whether our digital clock app was formatting times in a 12 hour or 24 format.
Your can see the actual code below where we sets it value based on the value of a ToggleSwitch.
isMilitaryTime = ToggleSwitch.IsOn;
IPropertySet appData = ApplicationData.Current.RoamingSettings.Values;
appData["MILITARYTIME"] = isMilitaryTime;
I had commented on the RoamingSettings by saying they are synced with the cloud. Imagine you had an app installed on more than one machine. If you change settings using RoamingSettings if will be shared with each instance of your app via notification from the cloud. This is a handy feature if your application is running on multiple clients for the same user.
Here were the two questions were:
1. Since the RoamingSettings are synced with the cloud how would we be notified if the app is running that a change occurred?
Good question. If you use Visual Studio IntelliSense (or the doc) you’ll see that ApplicationDataContainerSettings has an MapChanged event we can register for to be notified one any of the values stored in his object change. If your interested in any app data changes (not just settings) you want to use the ApplicationData classes DataChanged event.
How would I implement that?
In my application’s MainPage.xaml.cs constructor I added the following code to my constructor to provide an event handler for the MapChanged event, so when the ApplicationDataContainerSettings gets a MapChanged can respond to it.
IPropertySet appData = ApplicationData.Current.RoamingSettings.Values;
appData.MapChanged += appData_MapChanged;
Here is the implementation of my event handler.
void appData_MapChanged(IObservableMap<string, object> sender, IMapChangedEventArgs<string> @event)
{
IPropertySet appData = ApplicationData.Current.RoamingSettings.Values;if (appData.ContainsKey("MILITARYTIME"))
ToggleSwitch.IsOn = (bool)appData["MILITARYTIME"];
else
ToggleSwitch.IsOn = false;}
so now when the application settings contained in the ApplicationDataContainerSettings has a value changed we be notified and be able to response to it.
2. If we RoamingSettings and we are not connected to the internet what happens? (e.g. do we get an exception?)
There is caching if there is no internet connection, so we can set it fine without an Internet connection. When you have an connection again the roaming data will be sync with the cloud.