【发布时间】:2019-12-17 14:07:19
【问题描述】:
所以我要离开这个网站:Winsows 10 UWP: How to Read and Save Setting Easily - Edi.Wang
我尝试过使用
<Page.Resources>
<core:AppSettings x:Key="AppSettings"/>
</Page.Resources>
但我得到一个错误
Type 'AppSettings' is not usable as an object because it is not public or does not define a public parameterless constructor or a type converter.
这是我作为单例实现的 AppSettings 类,示例中没有。
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.Storage;
namespace MediaManager.Services
{
/// <summary>
/// Singleton class for handing application settings data.
/// </summary>
public class AppSettings : INotifyPropertyChanged
{
private static volatile AppSettings _instance;
private ApplicationDataContainer _localData = null;
private ApplicationDataContainer _roamingData = null;
private static object syncRoot = new object();
private AppSettings()
{
_localData = ApplicationData.Current.LocalSettings;
_roamingData = ApplicationData.Current.RoamingSettings;
}
public static AppSettings Instance
{
get
{
if (_instance is null)
lock (syncRoot)
if (_instance is null)
_instance = new AppSettings();
return _instance;
}
}
private void SaveSettings(string key, object value, bool roaming = false)
{
if (roaming)
_roamingData.Values[key] = value;
else
_localData.Values[key] = value;
}
private T ReadSetting<T>(string key, T defaultValue = default(T), bool roaming = false)
{
if (roaming)
{
if (_roamingData.Values.ContainsKey(key))
return (T)_localData.Values[key];
}
else if (_localData.Values.ContainsKey(key))
return (T)_localData.Values[key];
return defaultValue;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged([CallerMemberName]string propName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
// List all setting here
public string movie_staging_folder
{
get => ReadSetting<string>(nameof(movie_staging_folder), roaming: true);
set
{
SaveSettings(nameof(movie_staging_folder), value, true);
NotifyPropertyChanged();
}
}
}
}
我知道就像错误所说的那样,我的 appSettings.cs 没有公共构造函数;这是一个单例类。我不知道如何让数据绑定与单例类一起工作。
【问题讨论】:
-
为什么一定要单例?
-
@Stuart 根据我的阅读,
NotifyPropertyChanged如果不是单例则无法正常工作,因为如果存在多个 AppSetting 实例会出现并发症。
标签: c# xaml data-binding uwp singleton