无法在文件夹中找到图像

无法在文件夹中找到图像

本文介绍了无法在文件夹中找到图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在项目中添加一些新标志,所以我下载并将新图像插入 Images 文件夹中。每个图像名称都有 CountryData.cs 中可用的国家/地区ID,这是字典结构:

I need to add some new flag to this project, so I downloaded it and inserted the new image inside the Images folder. Each image name have the country ID available in CountryData.cs, this is the Dictionary structure:

private static readonly Dictionary<string, string> _englishNameByIso2 = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
    {
        {"AF", "Afghanistan"},
        {"AX", "Åland Islands"},
        {"AL", "Albania"},
        {"DZ", "Algeria"},
        {"AS", "American Samoa"},
        ...

现在我添加了一个新行: {CW,Curaçao}, 带有一个名为: cw.png 的图像文件,我可以在项目文件夹中看到。但是当执行此代码时:

now I added a new line: {"CW", "Curaçao"}, with an image file named: cw.png that I can see in the project folder. But when this code will be executed:

 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var countryId = value as string;

        if (countryId == null)
            return null;

        try
        {
            var path = $"/FamFamFam.Flags.Wpf;component/Images/{countryId.ToLower()}.png";
            var uri = new Uri(path, UriKind.Relative);
            var resourceStream = Application.GetResourceStream(uri);
            if (resourceStream == null)
                return null;

            var bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = resourceStream.Stream;
            bitmap.EndInit();
            return bitmap;
        }
        catch
        {
            return null;
        }
    }

它将返回 null 对于 IO异常,其他图像在 ComboBox 中正确显示。

it will return null for IO Exception, the other images are displayed correctly in the ComboBox.

我还尝试将新图像的动作构建更改为资源但无法正常工作。

I also tried to change the action build of the new image as resource but didn't worked.

图像中的图像文件夹没有设置的操作构建。我究竟做错了什么?我真的不明白为什么找不到新图像!

The image in the folder doesn't have an action build setted. What am I doing wrong? I really don't understand why the new image are not found!

推荐答案

将图像文件的构建操作设置为资源,并通过:

Set the image file's Build Action to Resource, and load it by a Resource File Pack URI:

var path = $"pack://application:,,,/FamFamFam.Flags.Wpf;component/Images/{countryId.ToLower()}.png";
var bitmap = new BitmapImage(new Uri(path));

这篇关于无法在文件夹中找到图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 22:40