wpf WPF加载图片时抛出“无法定位资源”异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11948829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:29:13  来源:igfitidea点击:

WPF throws "Cannot locate resource" exception when loading the image

wpfresources

提问by tete

I am having a WPF window, with a background image of one file in my local system. So the XAML file looks like this:

我有一个 WPF 窗口,在我的本地系统中有一个文件的背景图像。所以 XAML 文件看起来像这样:

 <Window.Background>
    <ImageBrush ImageSource="/MYASSEMBLY;component/Resources/MyPic.png"/>
 </Window.Background>

In the XAML designer it actually shows this background image, so the image does exist in MYASSEMBLY\Resources folder. However, in the InitializeComponent()function call when I launch the application, it throws the exception

在 XAML 设计器中,它实际上显示了此背景图像,因此该图像确实存在于 MYASSEMBLY\Resources 文件夹中。但是,在InitializeComponent()我启动应用程序时的函数调用中,它抛出异常

Cannot locate resource 'resources/mypic.png'.

找不到资源“resources/mypic.png”。

So I am totally lost now. Are the directories different between the design and runtime so doesn't exist in the runtime?

所以我现在完全迷失了。设计和运行时的目录是否不同,因此在运行时中不存在?

回答by Buzz

In Solution Explorer set the image file's Build Actionproperty to Resource. Then cleanthe solution and rebuild it.

在解决方案资源管理器中,将图像文件的Build Action属性设置为Resource. 然后清洁溶液并重建它。