如何在 Windows Metro 应用程序中使用 xml 解析在 Gridview 中绑定图像 [英] How to bind image in Gridview using xml parsing in windows metro app

查看:20
本文介绍了如何在 Windows Metro 应用程序中使用 xml 解析在 Gridview 中绑定图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发我的第一个 Windows 8 应用.我正在尝试显示填充了图像和图像描述的 GridView.我想从我创建的 XML 文件中获取我的数据.我找到了 GridView 的 ItemSource 属性,我尝试将我的 XML 文件绑定到它,但我不能这样做.

I'm working on my first Windows 8 app. I'm trying to display a GridView populated with Image and Image description. I want to get my data from an XML file I created. I found the ItemSource property of the GridView and I try to bind my XML file to it but I can't do this.

请告诉我执行此任务的正确方法.谢谢

Please tell me right way to do this task. thanx

推荐答案

不能将 XML 文件直接绑定到 GridView.ItemsSource,需要先将其解析为对象.我会创建一个类,其中包含要在 GridView 中显示的所有数据:

You can't bind an XML file directly to GridView.ItemsSource, you need to parse it first into an object. I'd create a class with all data to be displayed in GridView:

public class GridViewItem
{
    public string Description { get; set; }
    public ImageSource Image { get; set; }
}

下一步是将 XML 文件解析为 GridViewItem 的列表:

The next step is to parse the XML file into a list of GridViewItems:

var xmlString = await FileIO.ReadTextAsync(storageFile);
var xml = XDocument.Parse(xmlString);
var Items = xml.Element("rootNode").Elements("itemNode").Select(i => new GridViewItem
    {
        Description = (string)i.Element("descriptionNode"),
        Image = ParseImage(i.Element("imageNode"))
    }).ToList();

我假设您的 XML 中的标签是 rootNodeitemNodedescriptionNodeimageNode.另外我不知道你的图像数据是如何存储在 XML 中的.将其转换为 ImageSource 的逻辑应该在 ParseImage() 中.

I've assumed the tags in your XML are rootNode, itemNode, descriptionNode and imageNode. Also I don't know how your image data is stored in XML. The logic to convert it to an ImageSource should be in ParseImage().

剩下的唯一事情就是将上面的 Items 列表分配给视图模型中作为您 DataContext 的属性并将其绑定到 ItemsSource>:

The only thing left is to assign the Items list above to a property in your view model serving as you DataContext and bind it to ItemsSource:

<GridView ItemsSource="{Binding Items}" />

这是基本思路.我的回答中遗漏了很多细节,但根据您的问题,我能做到的最好.

This is the basic idea. There's a lot of details missing in my answer but that's best I can do based on your question.

这篇关于如何在 Windows Metro 应用程序中使用 xml 解析在 Gridview 中绑定图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆