Search code examples
winrt-xamltemplate10

Settings in Template10 App


I want to Create custom setting in Template10 app. Settings service isn't well documented, so I would like to ask what is best/recommended way to create custom setting for example I want to add setting where you can turn search history on or off it is just bool value. Before I have been using this to set settings in app: ApplicationData.Current.LocalSettings.Values["SettingName"] = true;

To get setting value I would just use:

(bool)ApplicationData.Current.LocalSettings.Value["SettingName"]; 

Solution

  • Take a look at the SettingsService class in the minimal or hamburger template, it should look like this:

    public class SettingsService
    {
        public static SettingsService Instance { get; }
        static SettingsService()
        {
            // implement singleton pattern
            Instance = Instance ?? new SettingsService();
        }
    
        Template10.Services.SettingsService.ISettingsHelper _helper;
        private SettingsService()
        {
            _helper = new Template10.Services.SettingsService.SettingsHelper();
        }
    
        // add your custom settings here like this:
        public bool SettingName
        {
            get { return _helper.Read(nameof(SettingName), false); }  // 2nd argument is the default value
            set { _helper.Write(nameof(SettingName), value); }
        }
    }
    

    As you can see, it implements a singleton pattern and uses a helper from Template10 to read and write values into the application settings. I have also added there a custom setting called SettingName.

    To use it in your ViewModel, create a private variable:

    private SettingsService _settings = SettingsService.Instance;
    

    and then use it in whichever method, getter or setter you want like this:

    var something = _settings.SettingName;  // read
    _settings.SettingName = true;  // write
    

    If you'd like to change the behavior of your app based on some setting, the recommended way is to do it in a setter in the SettingsService class. However, I can image situations where you would do that change directly in the ViewModel instead.