【问题标题】:How to use an xml file for image folder?如何将 xml 文件用于图像文件夹?
【发布时间】:2019-11-07 11:24:57
【问题描述】:

我对 WPF 和 XML 非常陌生。我有一个图像文件夹和一个 xml 文件(我的 XML 文件中有我的图像文件夹的名称和图像名称)。如何通过 xml 从文件中调用我的图像并用它们制作一个列表?

谢谢。 (我的图像文件夹放在我的桌面上,也放在 Project Debug 文件夹中。)

XML 示例

<Item>
    <Title>
        Image 1
    </Title>
    <Image>
        <Image FolderName="Images">1.jpg</Image>
    </Image>
</Item>

我卡住的地方。

void LoadImages()
    {
        XDocument xml = XDocument.Load("images.xml");

        picList = new List<Picture>();

        var pics = (from item in xml.Descendants("Item")
                     select new Picture
                     {

                         Title = (string)item.Element("Title").Value,
                         Img = (BitmapImage(?????????))item.Element("Image")???

                     }).ToList();

        foreach (var item in pics)
        {
            picList.Add(item);
        }

        imgList.ItemsSource = picList;
    }

我的图片课

     public class Picture
    {

        public BitmapImage Img { get; set; }
        public string Title { get; set; }
    }

【问题讨论】:

  • 不确定“调用我的图像”到底是什么意思。您显然必须读取 XML 文件,从 &lt;Image&gt; 元素构造文件路径,然后加载例如来自 Uri 的 BitmapImage 文件路径。
  • 我可以这样做。我只想通过 XML 文件来做。只是图像名称。 picList = new List(); picList.Add(new Picture() { Img = new BitmapImage(new Uri(@"C:\Users\myname\Desktop\Proje\Images\1.jpg")), Title = "No 1", }); imgList.ItemsSource = picList;
  • 很抱歉,我不知道如何以正确的方式发布我的代码。 :(

标签: c# xml wpf image


【解决方案1】:

将 XML 结构更改为如下所示,每个 &lt;Item&gt; 中只有一个 &lt;Image&gt; 元素。

<Item>
    <Title>Image 1</Title>
    <Image FolderName="Images">1.jpg</Image>
</Item>

那么这应该适用于相对图像路径:

public void LoadImages()
{
    imgList.ItemsSource = XDocument.Load("images.xml")
        .Descendants("Item")
        .Select(item =>
    {
        var title = item.Element("Title").Value;
        var folder = item.Element("Image").Attribute("FolderName").Value;
        var file = item.Element("Image").Value;
        var path = Path.Combine(folder, file);

        return new Picture
        {
            Title = title,
            Img = new BitmapImage(new Uri(path, UriKind.Relative))
        };
    });
}

如果您需要绝对文件路径,您可以将图像根文件夹添加到 Path.Combine 调用,并删除 UriKind.Relative

您还应该声明 Picture 类,如下所示,以便在可以传递给 Img 属性的类型范围内具有更大的灵活性:

public class Picture
{
    public ImageSource Img { get; set; }
    public string Title { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-06
    • 2020-06-09
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多