隔了很长时间再重看自己的代码,觉得好陌生。。以后要养成多注释的好习惯。。直接贴代码。。对不起( ▼-▼ )
保存保存:进行序列化后存入应用设置里
ApplicationDataContainer _appSettings = ApplicationData.Current.LocalSettings; //这个是保存一些页面输入信息
private async void Save_Click(object sender, RoutedEventArgs e)
{
if (userName.Text == "" || userAge.Text == "")
{
await new MessageDialog("请输入完整的信息").ShowAsync();
return;
}
ObservableCollection<School> education = new ObservableCollection<School>();
if (school1.IsChecked == true)
education.Add(new School() { Id = "id001", Name = school1.Content.ToString() });
if (school2.IsChecked == true)
{
education.Add(new School() { Id = "id002", Name = school2.Content.ToString() });
}
User user = new User()
{
Education = education,
Id = Guid.NewGuid().ToString(),//随机生成 前面用到过的
Name = userName.Text,
Age = Int32.Parse(userAge.Text),
Verified = false
}; //使用DataContractJsonDeSeriaLizer实现方式
string json = ToJsonData(user); //带参数的构造函数 //string json = user.Stringify();//这个是构造自定义的类的,此处用不到 info.Text = json;
_appSettings.Values["UserDataKey"] = json; //存放到应用设置里面
await new MessageDialog("保存成功").ShowAsync();
}
获取数据:从应用设置取出,进行反序列化取出信息
private async void Get_Click(object sender, RoutedEventArgs e)
{
if (!_appSettings.Values.ContainsKey("UserDataKey"))
{
await new MessageDialog("未保存信息").ShowAsync();
return;
}
string json = _appSettings.Values[“UserDataKey”].ToString(); //反序列化为实体类对象
User user = DataContractJsonSerializer<User>(json); //User user = new User(json);
string userInfo = "";
userInfo = "Id:" + user.Id + "Name:" + user.Name + "Age:" + user.Age;
foreach (School school in user.Education)
{
userInfo += "Education:" + "Id:" + school.Id + "name:" + school.Name;
}
await new MessageDialog(userInfo).ShowAsync();
} private T DataContractJsonSerializer<T>(string jsonString)
{
var ds = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ds.ReadObject(ms);
ms.Dispose();
return obj;
}
不贴了。。看的好难受。。以后再也不会这么敷衍了。大家多看看其他的也行。
收获:
ObservableCollection<>相对List<>来说,绑定到ListBox会自动刷新
也就是当你在进行增加、删除操作时,前台会动态的显示。
有需要源码(WP8.1)的可以下载。包含了JSON/Xml的两种(构造与不构造类)操作方式。。