虚位以待(AD)
虚位以待(AD)
首页 > 软件编程 > WindowsPhone/WindowsMobile > WP7 应用数据存储IsolatedStorage 篇

WP7 应用数据存储IsolatedStorage 篇
类别:WindowsPhone/WindowsMobile   作者:码皇   来源:互联网   点击:

Windows Phone 7 在独立存储(Isolated Storage)功能方面提供了两种数据存储方法:文件存储(IsolatedStorageFile)、键 值存储(IsolatedStorageSettings)。通过独立存储我们能够对应用程序数据进行保存,例如:用户设置、程序运行状
Windows Phone 7 在独立存储(Isolated Storage)功能方面提供了两种数据存储方法:文件存储(aspx" target=_blank>IsolatedStorageFile)、键/值存储(IsolatedStorageSettings)。通过独立存储我们能够对应用程序数据进行保存,例如:用户设置、程序运行状态等。本篇主要讲解IsolatedStorageSettings 使用方法。

     IsolatedStorageSettings 实际上是提供了一个Dictionary<TKey, TValue> 泛型类,通过键值Tkey 与数值TValue 的映射将应用程序的数据存储起来。首先在程序中通过IsolatedStorageSettings 类创建一个全局settings,同时再定义一个整型变量以便后续测试。

IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;int testInt = 10;

添加两个按键:一个用来为testInt 执行“+1”操作,另一个用来显示当前testInt 的值。

private void addBtn_Click(object sender, RoutedEventArgs e){    testInt++;}private void showBtn_Click(object sender, RoutedEventArgs e){    MessageBox.Show(testInt.ToString());}

     接下来再添加一个Save 按键,用于保存testInt 数值和TextBox 数值。先使用Contains(string key) 方法检查当前是否存在“textbox”键值,如果没有则使用Add(string key, object value) 方法添加该键值,键对应的数值类型可按开发需要自行定义,本例中则使用了String 和Int 两种类型。

private void saveBtn_Click(object sender, RoutedEventArgs e){        if (!settings.Contains("textbox"))    {        settings.Add("textbox", textBox.Text);    }    else    {        settings["textbox"] = textBox.Text;    }    if (!settings.Contains("integer"))    {        settings.Add("integer", testInt);    }    else    {        settings["integer"] = testInt;    }}

     当每次重新启动程序时,可以直接从settings 中获取相应数据。为保险起见使用TryGetValue<T>(string key, out T value) 获取指定键的值,若键值不存在会返回False。

public MainPage(){    InitializeComponent();    string textVal;    if (settings.TryGetValue<string>("textbox", out textVal))    {        textBox.Text = textVal;    }    else    {        textBox.Text = "No Text";    }    int intVal;    if (settings.TryGetValue<int>("integer", out intVal))    {        testInt = intVal;    }    else    {        testInt = 10;    }}

附上XAML 代码:

<TextBox x:Name="textBox" Width="460" Height="72" /><Button x:Name="addBtn" Content="Add" Width="160" Height="72"         Click="addBtn_Click"/><Button x:Name="showBtn" Content="Show" Width="160" Height="72"        Click="showBtn_Click"/><Button x:Name="saveBtn" Content="Save" Width="160" Height="72"        Click="saveBtn_Click"/>

测试运行

如果不进行保存,每次启动TextBox 都会显示“No Text”,testInt 数值为10。

nosave nosave2

点击“Save”后,退出程序重新进入,修改的内容便会保存下来。

save save2

相关资料

System.IO.IsolatedStorage

IsolatedStorageFile

相关热词搜索: WP7 应用数据存储IsolatedStorage 篇