使用C#在Metro应用中保存用户设置

时间:2012-10-19 16:12:43

标签: c# .net windows

我想在Metro应用程序的本地文件夹中编写用户选择的设置。我已完成下面的代码,但它无法正常工作。

保存设置的代码:

        void OnUnloaded(object sender, RoutedEventArgs args)
    {
        //code to save app settings.
        var localSettings = ApplicationData.Current.LocalSettings;
        localSettings.Values["playerPosition"] = playerPosition;
        localSettings.Values["aiPosition"] = aiPosition;
        localSettings.Values["selectedLevel"] = selectedLevel;
    }

读取设置的代码:

            var localSettings = ApplicationData.Current.LocalSettings;
        if ((localSettings.Values["playerPosition"]) == null)
        {
            localSettings.Values["playerPosition"] = 1;
            localSettings.Values["aiPosition"] = 1;
            localSettings.Values["selectedLevel"] = "1";

            playerPosition = aiPosition = 1;
            selectedLevel = "1";
        }
        else
        {
            playerPosition = (int)localSettings.Values["playerPosition"];
            aiPosition = (int)localSettings.Values["aiPosition"];
            selectedLevel = (string)localSettings.Values["selectedLevel"]; ----

显然我应该将这个localSettings变量保存在文件中。但是,我无法找到执行此操作的代码。此外,卸载事件是一个很好的地方,或者我应该将它移动到OnNavigatedFrom事件?有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

我还没有尝试过,但也许您可以查看此示例(应用设置示例): http://code.msdn.microsoft.com/windowsapps/App-settings-sample-1f762f49

它使用Windows.UI.ApplicationSettings命名空间。

修改 在MSDN上阅读this postquickstart之后,在我看来,您不需要保存文件,因为LocalSettings会为您处理此问题?你没有看到这种行为吗?