【问题标题】:Cannot locate image inside a folder无法在文件夹中找到图像
【发布时间】:2018-01-12 11:04:01
【问题描述】:

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

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 的图像文件,我可以在项目文件夹中看到它。但是这段代码什么时候会被执行:

 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;
        }
    }

它将为IO Exception返回null,其他图像在ComboBox中正确显示。

我也尝试将新图像的动作构建更改为资源,但没有成功。

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

【问题讨论】:

  • 你为什么重新问你的问题? stackoverflow.com/questions/48215860/…
  • @rene 可能会添加新的细节我得到帮助,不觉得吗?
  • 然后编辑您的旧问题。特别是有人可能会再次建议将文件标记为资源。
  • 我正在努力提高效率,我记得我之前在不同的环境中看到过这个,我从搜索是的开始,所以我可以提供一个我知道有答案的副本.在那个搜索中,您删除的问题弹出了。但是我收到了消息,我将停止搜索,我希望有人会发现您代码中的错字并将其作为答案。祝你好运!
  • @Muds 我知道.. 抱歉 rene,但我对这个我无法解决的问题有点沮丧,希望你没有接受 :)

标签: c# wpf io filepath


【解决方案1】:

将图片文件的Build Action设置为Resource,并通过Resource File Pack URI加载:

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

【讨论】:

  • 您的意思是嵌入式资源?将其更改为 Resource 以使用 Pack URI。这就是WPF中加载图片文件资源的方式。
  • 我也有这个问题,你能帮帮我吗?
猜你喜欢
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
相关资源
最近更新 更多