11

我正在将按钮的内容设置为图像。它看起来像这样:

<Button>
   <Image Source="pack://application:,,,/NavigationImages/nav_up_left.png" />
</Button>

在我的项目中,我有一个名为 NavigationImages 的子文件夹,在该文件夹中是图像文件 nav_up_left.png。

当我查看设计器时,图像会出现,但是在运行时我收到一个 IOException 错误,说它找不到资源。

构建操作设置为资源。

实际上,这在一个项目中运行良好。但是当我将它复制到另一个项目时它失败了。这似乎是一个非常简单的问题,但我发现自己被难住了,准备开始拔头发。@_@

您的想法和建议将不胜感激!

4

4 回答 4

11

Whelp,我想通了......有点。

我将 xaml 代码从输出类型为 Windows 应用程序的一个项目复制到另一个输出类型为类库的项目中。

当时我没有想到,但显然当输出类型是类库时,pack URI 需要更改。

所以"pack://application:,,,/NavigationImages/nav_up_left.png"我没有把它改成"/ProjectName;component/NavigationImages/nav_up_left.png"现在它工作得很好。

我不是 100% 清楚为什么这是有效的,而不是前者。我已经阅读了关于 WPF 中包 URI 的 MSDN 文档,但也许我误解了一些东西。

如果有人能给我一个很好的解释,为什么我以前的东西在输出类型类库的项目中不起作用,我将不选中这个答案。

我可能错过了一些非常简单的东西。@_@

于 2011-07-26T22:18:59.657 回答
5

我只是在同一个问题上挣扎了很长一段时间,我认为原版中出现问题的部分原因是缺少“组件”这个词。例如,我有

myBitmapImage.UriSource = new Uri(@"pack://application:,,,/MyApp;images/mona2.jpg");

应该

... = new Uri(@"pack://application:,,,/MyApp;component/images/mona2.jpg");

The word "component" is not part of the pathname, despite its appearance -- it's a string literal that has to be there. Why? Someone thought it'd be a good idea, I guess.

And for those struggling with another part of the thing, what about "MyApp"? That's the name of the Assembly. Right-click on your project name, select "Properties...", and under the "Application" tab you'll see the "Assembly name:" field.

If you don't feel like searching for that (or worry that it might change, breaking your code), you can do this:

String appUri = @"pack://application:,,,/" + 
                  System.Reflection.Assembly.GetEntryAssembly().GetName().Name + ";";
String path = appUri + "component/images/mona2.jpg";
myBitmapImage.UriSource = new Uri(path);

Not very pretty code, I admit -- it can clearly be shortened -- but it'll gets you where you need to go, I hope. Remember to set the "Build" property on your image file to "Resource"!

于 2013-10-30T19:14:24.507 回答
2

只是为了阐明您的情况。第二包uri。那个起作用的。适用于位于程序集中的资源,而不是宿主应用程序。听上去,宿主应用程序是从有问题的类库中加载这个资源的吗?

您可以在此处查看 pack uri 方案的差异: MSDN Pack URI Scheme

当从主程序集中引用资源并从另一个程序集中引用资源时,uri 会略有变化。

此外,pack://application:,,, 包括所谓的“权限”,省略它基本上会使其成为一个相对路径,在假设应用程序权限的大多数情况下,两者都是有效的。

编辑:基本上是因为 /Subfolder/Resource.xaml(.jpg etc.) 和 /Assembly;component/Resource.xaml 非常相似,后者告诉解析器/加载器它正在查看引用的程序集,而不是在主应用程序的程序集中. (我想这有助于加快搜索速度)。

于 2013-02-22T00:42:24.010 回答
1

解决此问题的另一种解决方案:

将图像构建操作设置为“资源”并重新构建后,导航到<Image />对象的属性。属性窗口将提供一个...文件资源浏览器,然后选择您的图像,您的Source="..."属性<Image />将被正确填写。

于 2012-08-16T23:42:23.040 回答