Abdousamad Abdousamad - 9 months ago 37
C# Question

Application settings binding best practices

I've been struggling for a while now with how to best "interact" with settings on a binding level in a WinRT/UWP app. I've been looking for best practices regarding this, but I haven't found clear answers. What I've done so far in my apps is the following:


  1. Define a BindableBase which implements INotifyPropertyChanged.

  2. Create an AppSettings class which inherits from BindableBase and looks a bit like this:

    public class AppSettings : BindableBase
    {
    ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;

    public string MySetting
    {
    get
    {
    if (!localSettings.Values.ContainsKey("MySetting"))
    localSettings.Values["MySetting"] = "Some default value";

    return localSettings.Values["MySetting"].ToString();
    }
    set
    {
    localSettings.Values["MySetting"] = value;
    RaisePropertyChanged();
    }
    }
    }

  3. Define a ViewModel which has a an AppSettings property:

    public class SettingsViewModel
    {
    public AppSettings Settings { get; set; } = new AppSettings();
    }

  4. Bind to the Settings property in the View:

    <TextBlock Text="{Binding Settings.MySetting, Mode=TwoWay}">



I've seen and used implementations in the past that had a settings service, but these applications didn't need the settings changes to go in effect immediately. So what I'm basically asking is: If changes to settings should go immediately into effect, is the above implementation a good way to bind to settings? If not, what do you recommend?

Answer Source

This seems fine in a general case. The only thing I'd change would be to only raise the notification if the data actually changes:

set
{
    if (MySetting != value)
    {
        localSettings.Values["MySetting"] = value;
        RaisePropertyChanged();
    }
}

This will avoid raising notifications unnecessarily.
Depending on the frequency the values are read, you may want to keep your own in memory copy of the setting values (in a private field) instead of reading them from the container each time.