应用程序设置绑定最佳实践

Men*_*ens 3 c# xaml mvvm windows-runtime uwp

一段时间以来,我一直在努力解决如何与 WinRT/UWP 应用程序中的绑定级别的设置进行最佳“交互”。我一直在寻找与此相关的最佳实践,但尚未找到明确的答案。到目前为止,我在我的应用程序中所做的事情如下:

  1. 定义一个实现 INotifyPropertyChanged 的​​ BindableBase。
  2. 创建一个继承自 BindableBase 的 AppSettings 类,看起来有点像这样:

    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();
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 定义一个具有 AppSettings 属性的 ViewModel:

    public class SettingsViewModel
    {
        public AppSettings Settings { get; set; } = new AppSettings();
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 绑定到视图中的 Settings 属性:

    <TextBlock Text="{Binding Settings.MySetting, Mode=TwoWay}">
    
    Run Code Online (Sandbox Code Playgroud)

我过去见过并使用过具有设置服务的实现,但这些应用程序不需要设置更改立即生效。所以我基本上要问的是:如果对设置的更改应立即生效,那么上述实现是绑定到设置的好方法吗?如果没有,你有什么推荐?

小智 5

我受到这篇文章的启发,所以我想出了一些更优雅的东西,以避免多次复制和粘贴属性名称(键)。我使用以下内容:

public class SettingsViewModel : BindableBase
{
    public string MyProperty
    {
        get
        {
            return Get("MyProperty", "SomeDefaultValue");
        }
        set
        {
            Set("MyProperty", value);
        }
    }

    public T Get<T>(string PropertyName, T DefaultValue)
    {
        //If setting doesn't exist, create it.
        if (!App.Settings.ContainsKey(PropertyName))
            App.Settings[PropertyName] = DefaultValue;

        return (T)App.Settings[PropertyName];
    }

    public void Set<T>(string PropertyName, T Value)
    {
        //If setting doesn't exist or the value is different, create the setting or set new value, respectively.
        if (!App.Settings.ContainsKey(PropertyName) || !((T)App.Settings[PropertyName]).Equals(Value))
        {
            App.Settings[PropertyName] = Value;
            OnPropertyChanged(PropertyName);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

假设您的App类定义了以下属性:

public static IPropertySet Settings
{
    get
    {
        return Windows.Storage.ApplicationData.Current.LocalSettings.Values;
    }
}
Run Code Online (Sandbox Code Playgroud)

后者比书写更方便,

ApplicationData.Current.LocalSettings.Values
Run Code Online (Sandbox Code Playgroud)

并且仍然可以在全球范围内访问。