漫谈windows phone 7 独立存储(二)
在上篇文章中,我们谈了IsolatedStorageFile,今天我们来看一下IsolatedStorageSettings的用法。IsolatedStorageSettings可以说是保存数据到独立存储最简单的方式,如果是键值对的数据类型,并想要持久地保存在独立存储中,这时就可以使用IsolatedStorageSettings。
当退出应用时,应用的配置内容会自动序列化至独立存储中的一个文件内,当应用launched或者activated时,又会使用先前的数据来填充字典。
在本例中,我们将对IsolatedStorageSettings进行CRUD操作。
XAML:
Code
CS:
Codeusing System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
namespace IsolatedStorageSettingsDemo
{
public partial class MainPage : PhoneApplicationPage
{
private IsolatedStorageSettings _appSetting;
// Constructor
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait;
_appSetting = IsolatedStorageSettings.ApplicationSettings;
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(txtKey.Text))
{
if (_appSetting.Contains(txtKey.Text))
{
_appSetting = txtValue.Text;
}
else
{
_appSetting.Add(txtKey.Text, txtValue.Text);
}
_appSetting.Save();
BindKeyList();
}
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
if (lstKeys.SelectedIndex > -1)
{
_appSetting.Remove(lstKeys.SelectedItem.ToString());
_appSetting.Save();
BindKeyList();
}
}
private void BindKeyList()
{
lstKeys.Items.Clear();
foreach (string key in _appSetting.Keys)
{
lstKeys.Items.Add(key);
}
txtKey.Text = "";
txtValue.Text = "";
}
private void lstKeys_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
string key = e.AddedItems.ToString();
if (_appSetting.Contains(key))
{
txtKey.Text = key;
txtValue.Text = _appSetting.ToString();
}
}
}
}
}
效果图:
页:
[1]