在這個(gè)小教程,我將演示在Windows Phone 7如何讓ListBox的數(shù)據(jù)綁定XML數(shù)據(jù)。我將使用LINQ to XML,以便加載和讀取數(shù)據(jù),而且我將展示如何實(shí)現(xiàn)一個(gè)基本的過濾。
首先讓我們先創(chuàng)建一個(gè)Windows Phone 7的應(yīng)用程序項(xiàng)目示例,并添加以下兩個(gè)demo xml文件。
people.xml
<?xml version="1.0" encoding="utf-8" ?> <people> <person> <firstname>Kate</firstname> <lastname>Smith</lastname> <age>27</age> </person> <person> <firstname>Tom</firstname> <lastname>Brown</lastname> <age>30</age> </person> <person> <firstname>Tim</firstname> <lastname>Stone</lastname> <age>36</age> </person> <person> <firstname>Ann</firstname> <lastname>Peterson</lastname> <age>27</age> </person> </people>
在這里我不得不感謝一直支持我的鹵面網(wǎng)版主,是他讓我提起興趣寫了這么一篇文章,再次感謝鹵面網(wǎng),一個(gè)非常不錯(cuò)的wp7開發(fā)論壇,后面我也將再次向大家發(fā)布幾篇高質(zhì)量文章,請(qǐng)大家到鹵面上找我吧,呵呵
進(jìn)入正題:
PeopleCustom.xml
<?xml version="1.0" ?> <People> <Person FirstName="Kate" LastName="Smith" Age="27" /> <Person FirstName="Tom" LastName="Brown" Age="30" /> <Person FirstName="Tim" LastName="Stone" Age="36" /> <Person FirstName="Ann" LastName="Peterson" Age="27" /> </People>
下一步是創(chuàng)建一個(gè)示例類將被用來存儲(chǔ)XML元素值:
public class Person { string firstname; string lastname; int age; public string FirstName { get { return firstname; } set { firstname = value; } } public string LastName { get { return lastname; } set { lastname = value; } } public int Age { get { return age; } set { age = value; } } }
為了讀取XML文件的信息,我們將使用的XDocument
所以你首先需要添加System.Xml.Linq.dll引用,然后using System.Xml.Linq;
XDocument loadedData = XDocument.Load("People.xml"); var data = from query in loadedData.Descendants("person") select new Person { FirstName = (string)query.Element("firstname"), LastName = (string)query.Element("lastname"), Age = (int)query.Element("age") }; listBox.ItemsSource = data;
在接下來的例子中,我們將通過數(shù)據(jù)的“年齡”屬性值過濾。源代碼如下:
XDocument loadedCustomData = XDocument.Load("PeopleCustom.xml"); var filteredData = from c in loadedCustomData.Descendants("Person") where c.Attribute("Age").Value == "27" select new Person() { FirstName = c.Attribute("FirstName").Value, LastName = c.Attribute("LastName").Value }; listBox1.ItemsSource = filteredData;
為了顯示的數(shù)據(jù),我們將使用以下ItemTemplates綁定ListBox控件:
<StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" Orientation="Horizontal"> <TextBlock Text="XML Data:"/> <ListBox x:Name="listBox"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Margin="10" > <TextBlock Text="{Binding FirstName}"/> <TextBlock Text="{Binding LastName}"/> <TextBlock Text="{Binding Age}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <TextBlock Text="Filtered by Age 27:"/> <ListBox x:Name="listBox1"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Margin="20" > <TextBlock Text="{Binding FirstName}"/> <TextBlock Text="{Binding LastName}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </StackPanel>