<metro>Application Data

      Application Data样例显示了如何存储和检索数据,是特定于metro风格的,在Windows运行程序中的数据编程接口API。

                                             图1

       如图1,用户数据在一个应用程序中可以被存储为文件。有本地(local)/漫游(roaming)/临时的(temporary)三种。

                                            图2

       如图2,Settings主要是存储程序中的键值对。可以是localSettings本地设置,或是roamingSettings漫游设置。如写入设置“HelloWorld”。同时,单击“Delete setting”键会删除。如图3.

                     

                                            图3

        如图4,Setting Containers 设置容器实质上是组的设置,是很常用的一种组织形式。用createContainer和deleteContainer删除容器来读/写/删一些设置容器。

                                              图4

        当击中Increment-Click事件方法后,Counter计数器开始增加,StorageFile存储文件实例化一个文件file,等待await漫游文件夹创建一个异步文件,等待文件异步输入。然后输出DisplayOutput()。它会调用ReadCounter()方法,随即输出文本。

Files.xaml.cs
        async void Increment_Click(Object sender, RoutedEventArgs e)        {            counter++;            StorageFile file = await roamingFolder.CreateFileAsync(filename,      CreationCollisionOption.ReplaceExisting);            await FileIO.WriteTextAsync(file, counter.ToString());            DisplayOutput();        }        async void ReadCounter()        {            try{                StorageFile file = await roamingFolder.GetFileAsync(filename);                string text = await FileIO.ReadTextAsync(file);                OutputTextBlock.Text = "Counter: " + text;                counter = int.Parse(text); }            catch (Exception) {                OutputTextBlock.Text = "Counter: <not found>";        }}

 

       Settings.xaml.cs中,单击writeSetting-Click,会写入文本“Hello World”并输出。单击DeleteSetting_click,会清空文本并输出。

       void WriteSetting_Click(Object sender, RoutedEventArgs e)
        {
            localSettings.Values[SettingName] = "Hello World"; // example value

            DisplayOutput();
        }

        void DeleteSetting_Click(Object sender, RoutedEventArgs e)
        {
            localSettings.Values.Remove(SettingName);

            DisplayOutput();
        }

 

SettingContained.xaml.cs中文本输出样式。

 void DisplayOutput()
        {
            bool hasContainer = localSettings.Containers.ContainsKey(containerName);
            bool hasSetting = hasContainer ? localSettings.Containers[containerName].Values.ContainsKey(settingName) : false;

            String output = String.Format("Container Exists: {0}\n" +
                                          "Setting Exists: {1}",
                                          hasContainer ? "true" : "false",
                                          hasSetting ? "true" : "false");

            OutputTextBlock.Text = output;
        }

 

posted @ 2012-08-31 16:22  伍锋  阅读(263)  评论(0编辑  收藏  举报