Data binding User Settings in Windows Phone applications


 image

The canonical example of user settings is a “Show this welcome screen at startup” checkbox so that your application can offer a nice out-of-box experience.

By writing a simple type with some properties, adding a few helper files, and setting up a two-way data binding, you can store any settings without having to write special code.

Here’s what the completed project’s two-way data binding looks like for the checkbox:

  1. <CheckBox
  2. IsChecked="{Binding Source={StaticResource MySettings}, Path=IsFirstRun, Mode=TwoWay}"
  3. Content="Show this page at startup"
  4. />
  • Source is a static resource, a strongly typed settings class you define
  • Path points to the property name to bind to
  • Binding is two-way so that the value is stored automatically
  • Value and type converters can be applied as always in bindings if necessary
Creating your configuration/settings type

Next, we need to create a strongly typed configuration class that derives from my SettingsProvider type. This class must:

  • Implement INotifyPropertyChanged, so that bindings work well
  • Have properties of the appropriate type for the settings you are interested in. Optionally, include the DefaultValue attribute to provide defaults.
  1. using System.ComponentModel; 
  2. using JeffWilcox.Settings; 
  3. namespace Sample 
  4. /// <summary>
  5. /// My settings class for storing application data and setting specific to
  6. /// the user.
  7. /// </summary>
  8. public class MySettings : SettingsProvider 
  9.     { 
  10. private bool _isFirstRun; 
  11. private string _hello; 
  12. public MySettings() : base("MySettings.xml") { } 
  13.         [DefaultValue("What’s up?")] 
  14. public string HelloWorld 
  15.         { 
  16. get { return _hello; } 
  17. set
  18.             { 
  19.                 _hello = value; 
  20.                 NotifyPropertyChanged("HelloWorld"); 
  21.             } 
  22.         } 
  23.         [DefaultValue(true)] 
  24. public bool IsFirstRun 
  25.         { 
  26. get { return _isFirstRun; } 
  27. set
  28.             { 
  29. bool old = _isFirstRun; 
  30.                 _isFirstRun = value; 
  31. if (value != old) 
  32.                 { 
  33.                     NotifyPropertyChanged("IsFirstRun"); 
  34.                 } 
  35.             } 
  36.         } 
  37.     } 

Via Jeff Wilcox – Data binding user settings in Windows Phone applications

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s