Win8 Metro 开发,需要用到数据绑定
想到了LINQ TO XML
以下简单的例子说明如何加载XML--》读取XML--》页面绑定
1。
在项目根目录新建一文件夹,命名为XML,文件夹内放置一 Resource.xml 文件,格式如下:
<?xml version="1.0" encoding="utf-8" ?>
<park>
<Company>
<Id>C0001</Id>
<Name>Comany 1</Name>
<Introduction>
Introduction 1
</Introduction>
<ImageUrl>Images/Company/C0001.jpg</ImageUrl>
<PointX>31.489495</PointX>
<PointY>120.373496</PointY>
</Company>
</park>
2. 加载此XML:
public static class XmlHelper
{
public static async Task<XDocument> LoadXml()
{
StorageFolder storageFolder = await Package.Current.InstalledLocation.GetFolderAsync("XML");
StorageFile storageFile = await storageFolder.GetFileAsync("Resource.xml");
XmlLoadSettings loadSettings = new XmlLoadSettings();
loadSettings.ProhibitDtd = false;
loadSettings.ResolveExternals = false;
XmlDocument xmlDoc = await XmlDocument.LoadFromFileAsync(storageFile, loadSettings);
XDocument doc = XDocument.Parse(xmlDoc.GetXml());
var ReturnTask = Task.Factory.StartNew(() => doc);
return await ReturnTask;
}
}
3。查询XML:
/// <summary>
/// Search resource
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
public static async Task<List<ParkData>> SearchResource(string query)
{
XDocument doc = await LoadXml();
var result = doc.Descendants("park").Elements()
.Where(x => x.Element("Name").Value.Contains(query))
.Select(x => new ParkData
{
Id = x.Element("Id").Value,
CompanyName = x.Element("Name").Value,
ImageURL = x.Element("ImageUrl").Value,
Introduction = x.Element("Introduction").Value,
PointX = x.Element("PointX").Value,
PointY = x.Element("PointY").Value
});
var ReturnTask = Task.Factory.StartNew(() => result.ToList());
return await ReturnTask;
}
页面调用:
List<ParkData> parkdata=await XmlHelper.SearchResource(this.txbSearch.Text);
总体的流程就是这样,此处权当抛砖引玉