关闭应用程序后,组合设置值未保存

时间:2017-01-27 19:56:40

标签: c# uwp win-universal-app

在保存功能结束时,可以正确保存和检索复合设置。但是,在关闭Visual Studio运行时实例并再次运行项目后,复合值将恢复为默认值。这可能有什么问题?

保存

private void SaveSettings()
    {
        var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
        var compositeTest = (Windows.Storage.ApplicationDataCompositeValue)localSettings.Values["Test"];

        // Save test
        compositeTest["A"] = PropA;
        compositeTest["B"] = PropB;
        compositeTest["C"] = PropC;

        // Retrieve test
        var a = compositeTest["A"];
        var b = compositeTest["B"];
        var c = compositeTest["C"];
}

构建

private void BuildSettings()
    {
        var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
        var compositeTest = (Windows.Storage.ApplicationDataCompositeValue)localSettings.Values["Test"];

            if (compositeTest == null)
            {
                Windows.Storage.ApplicationDataCompositeValue composite = new Windows.Storage.ApplicationDataCompositeValue();

                composite["A"] = PropA= 1;
                composite["B"] = PropB= 1;
                composite["C"] = PropC= 1;

                localSettings.Values["Test"] = composite;
            }
            else
            {
                PropA= (int)compositeTest["A"];
                PropB= (int)compositeTest["B"];
                PropC= (int)compositeTest["C"];
            }
 }

1 个答案:

答案 0 :(得分:3)

您需要将合成设置添加到IPropertySet的值LocalSettings

private void SaveSettings()
{
    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    var compositeTest = new Windows.Storage.ApplicationDataCompositeValue();

    compositeTest["A"] = "A";

    localSettings.Values["Test"] = compositeTest;

}

private void BuildSettings()
{
    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    var compositeTest = localSettings.Values["Test"] as Windows.Storage.ApplicationDataCompositeValue;

    var a = compositeTest["A"];
}

修改:尝试重置localSettings.Values["Test"]方法中的SaveSettings()密钥:

private void SaveSettings()
{
    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    var compositeTest = (Windows.Storage.ApplicationDataCompositeValue)localSettings.Values["Test"];

    // Save test
    compositeTest["A"] = PropA;
    compositeTest["B"] = PropB;
    compositeTest["C"] = PropC;

    // Retrieve test
    var a = compositeTest["A"];
    var b = compositeTest["B"];
    var c = compositeTest["C"];

    localSettings.Values["Test"] = compositeTest;
}