Windows 8 Metro Development (04): Save/read local application settings

Source: Internet
Author: User
The Jos? Mourinho column is http://blog.csdn.net/zyc13701469860.
Sometimes we need to save the application settings, such as the user's system settings. In Android, we can use sharepreference. What should we do in Metro? Save/read basic dataThe Metro program writes the data to be saved to the applicationdata. Current. localsettings dictionary and saves it locally. The dictionary is initialized locally when the program starts running. Load the previously saved data. In this way, we can easily save/read basic data types. I encapsulated it into a tool class.
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. threading. tasks; using Windows. storage; namespace win8_study.pages {class localdatautil {# region save/read basic type data public static void savedata (string key, object Value) {applicationdata. current. localsettings. values [Key] = value;} public static object getdata (string key) {return applicationdata. current. localsettings. values [Key];} public static void removedata (string key) {applicationdata. current. localsettings. values. remove (key) ;}# endregion }}

Here is an example:
The default font size is 24. We change the font size to 28 and return to the home page, and then enter the page again. You will find that the font size is changed to 28. Restart the program to enter the page and you will find that the font size is still 28. The selected items in the drop-down list correspond to the font size at all times.
The implementation method is as follows:: 1. each time you enter the page, first obtain the previously saved font size. the default font size is not set to B. set the font size to the obtained value. 2. the user changes the font size and saves the changed value.
Public sealed partial class localdatapage: bytes {private readonly string text_value = "guo mi _ Baidu Baike \ n" + "football club Internazionale Milano (Inter or Internazionale) "+" is a football club located in Milan, lunbadi district, northern Italy. "; Private readonly double text_font_size = 24; private readonly string text_font_size_key =" LocalDataPage-TEXT_FONT_SIZE_KEY "; Public localdatapage () {This. initializecomponent ();} protected override void loadstate (Object navigationparameter, Dictionary <string, Object> pagestate) {Init ();} private void Init () {// read the previously saved settings. If it is null, it is set to the default status initfontsize (); lefttextblock. TEXT = text_value;} protec Ted override void savestate (Dictionary <string, Object> pagestate) {}# region save program setting private void onleftcomboboxselectionchanged (Object sender, selectionchangedeventargs e) {var ComboBox = sender as ComboBox; vaR item = ComboBox. selecteditem as comboboxitem; settextfontsize (convert. todouble (item. content);} private void settextfontsize (double size) {lefttextblock. fontsize = size; localdatautil. Savedata (text_font_size_key, size);} private void initfontsize () {var OBJ = localdatautil. getdata (text_font_size_key); double size = text_font_size; If (OBJ! = NULL) {size = convert. todouble (OBJ);} foreach (VAR element in leftfontsizecombobox. items) {var item = element as comboboxitem; If (item. content. tostring (). equals (size. tostring () {leftfontsizecombobox. selecteditem = item; break; }}# endregion ...}

Maybe you will try to use this method to get non-basic data (such as page, color or something ). Hey, let's go. How can we save non-basic data? For example, a set of student information?

Save/read non-basic data-serialization/deserializationIt is necessary to save the real-time data of the program. For example, if you get some entertainment news from the Internet and display it to users, you need to save the data so that the program can be used at the next operation. The next time you run the program, the data will become local, and the loading speed will be very fast, because you do not need to get data from the network. If you do not, the user may see a very "clean" screen when the network is very congested. At this time, your application may be (should be required )...
For example, there are two classes, student and coder, which all inherit from the parent class people.
using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.Text;using System.Threading.Tasks;namespace Win8_Study.Pages{    [DataContract]    public abstract class People    {        [DataMember]        public string Name { get; set; }        [DataMember]        public int Age { get; set; }        public People(string name,int age)        {            this.Name = name;            this.Age = age;        }    }    [DataContract]    public class Student : People    {        [DataMember]        public int Score { get; set; }        public Student(string name, int age, int score)            : base(name, age)        {            this.Score = score;        }    }    [DataContract]    public class Coder : People    {        [DataMember]        public int WorkYears { get; set; }        public Coder(string name, int age, int workYears)            : base(name, age)        {            this.WorkYears = workYears;        }    }}

We need to randomly display some student and programmer information on the listview and save it. Then clear the listview and read the saved data to check whether the result is the same as the previous one.

The method for creating student and programmer information is very simple. Here, 5-10 pieces of information are created, and the content of each piece of information is displayed at random:

Private list <people> getpeopledatas () {list <people> tables les = new list <people> (); random ran = new random (datetime. now. millisecond); int COUNT = ran. next (5) + 5; // 5-10 for (INT I = 0; I <count; ++ I) {int type = ran. next (2); If (type = 0) {les. add (new student ("student" + (I + 1), ran. next (12) + 6, 60 + ran. next (41);} else {les. add (New coder ("programmer" + (I + 1), ran. next (10) + 22, ran. next (5);} return records les ;}

Create different listview items by category

private void OnRightRandomAddDataButtonClicked(object sender, RoutedEventArgs e)        {            _peoples = GetPeopleDatas();            SetListViewData(_peoples);        }
Private void setlistviewdata (list <people> tables les) {itemlistview. items. clear (); foreach (People P in minutes les) {listviewitem item = new listviewitem (); item. fontsize = 20; If (P is student) {student s = P as student; item. content = string. format ("{0} age: {1} score: {2}", S. name, S. age, S. score);} else {coder c = P as coder; item. content = string. format ("{0} age: {1} working time: {2} years", C. name, C. age, C. workyears);} itemlistview. items. add (item );}}


Save data

Private async void onrightsavedatabuttonclicked (Object sender, routedeventargs e) {await serializerutil. xmlserialize (_ cmdles, typeof (list <people>); await popuputil. showmessagedialog (string. format ("data saved! Number of items {0} ", _ Les. Count)," prompt ");}

Have you noticed the serialization flag in people, student, and coder? If this parameter is not added, it cannot be serialized. Serializerutil. xmlserialize is the method of encapsulating the serialization Code. Its implementation is as follows:

Public static async task xmlserialize (object instance, type) {// obtain the directory where the current program stores data storagefolder folder = windows. storage. applicationdata. current. localfolder; // define the file name string filename = "LocalDataPage-list_data.xml"; // create a file that overwrites storagefile newfile = await folder if the file exists. createfileasync (filename, creationcollisionoption. replaceexisting) // serialize the content to the file stream newfilestream = await newfile. openstreamforwriteasync (); datacontractserializer SER = new datacontractserializer (type, gettypes (); Ser. writeobject (newfilestream, instance); newfilestream. dispose ();}

Note that the gettypes () method specifies the type set of the serialized object during serialization. There are three data types to be serialized: People, student, and coder. So we should set it as follows:

Private Static observablecollection <type> gettypes () {// Add if (_ types = NULL) {_ types = new observablecollection <type> (); _ types. add (typeof (people); _ types. add (typeof (student); _ types. add (typeof (CODER);} return _ types ;}

_ Types is the Global Object observablecollection <type>. Now, the data is saved.
Read dataReading data is deserialization. We can get the previously saved object set, whose data type is list <people>. Then we can give the object set to listview for display.

Private async void onrightloaddatabuttonclicked (Object sender, routedeventargs e) {try {var OBJ = await serializerutil. xmldeserialize (typeof (list <people>); _ parameters les = OBJ as list <people>; setlistviewdata (_ parameters les); await popuputil. showmessagedialog (string. format ("data read successful! Number of items {0} ", _ items Les. Count)," prompt "); return;} catch (filenotfoundexception) {} await popuputil. showmessagedialog (" You have not saved the data. "," Prompt ");}

Deserialization

Public static async task <Object> xmldeserialize (type) {storagefolder folder = windows. storage. applicationdata. current. localfolder; string filename = "LocalDataPage-list_data.xml"; storagefile newfile = await folder. getfileasync (filename); stream newfilestream = await newfile. openstreamforreadasync (); // deserialize datacontractserializer SER = new datacontractserializer (type, gettypes (); object instance = Ser. readobject (newfilestream); newfilestream. dispose (); Return instance ;}

We can see that the read data is the same as the previously saved data. Our goal is achieved.
The program running effect is as follows: 1. The student and programmer information is displayed randomly:

2. Save the data to save the file content

<Arrayofpeople xmlns = "http://schemas.datacontract.org/2004/07/Win8_Study.Pages" xmlns: I = "http://www.w3.org/2001/XMLSchema-instance"> <people I: type = "student"> <age> 14 </age> <name> Student 1 </Name> <score> 66 </score> </People> <people I: type = "coder"> <age> 24 </age> <Name> programmer 2 </Name> <workyears> 4 </workyears> </People> <people I: type = "student"> <age> 7 </age> <Name> Student 3 </Name> <score> 86 </score> </People> <people I: type = "coder"> <age> 23 </age> <Name> programmer 4 </Name> <workyears> 1 </workyears> </People> <people I: type = "coder"> <age> 25 </age> <Name> programmer 5 </Name> <workyears> 2 </workyears> </People> </arrayofpeople>
3. Clear the data and read the previously saved data. The display effect is the same as that in the first figure.

Http://blog.csdn.net/zyc13701469860/article/details/8194090


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.