如何从XAML引用嵌入式资源?

eri*_*hak 24 .net c# wpf xaml embedded-resource

我有几个图像,我想嵌入到exe中.

当我将构建操作设置为嵌入式资源时, 我解决了代码中出现资源不可用的错误,并要求我将构建操作设置为资源

我尝试了几种不同的方法:

 <ImageSource x:Key="Image_Background">YearBook;component/Resources/Images/darkaurora.png</ImageSource>

 <ImageSource x:Key="Image_Background">Images/darkaurora.png</ImageSource>

 <ImageSource x:Key="Image_Background">pack://application:,,,/Resources/Images/darkaurora.png</ImageSource>
Run Code Online (Sandbox Code Playgroud)

此代码位于Resource文件中.但没有一个工作,他们都抛出这个错误:

Cannot convert the string 'pack://application:,,,/Resources/Images/darkaurora.png' into a 'System.Windows.Media.ImageSource' object. Cannot locate resource 'resources/images/darkaurora.png'.  Error at object 'Image_Background' in markup file 'YearBook;component/Resources/ImageResources.xaml' Line 4 Position 6.
Run Code Online (Sandbox Code Playgroud)

在代码中的不同位置我得到:

the file 'YearBook;component/Resources/Images/shadowdrop.png' is not a part of the project or its 'Build Action' property is not set to 'Resource'
Run Code Online (Sandbox Code Playgroud)

那么,我做错了什么?

yo *_*han 21

BuildAction设置为Resource时,它将作为程序集中的嵌入资源.或者,您可以将BuildAction设置为Content,然后将其捆绑到生成的.xap文件中.您可以使用这些BuildActions中的任何一个.通过将BuildAction设置为Content,您可以访问Image,如:( "/Resources/Images/darkaurora.png"必须以斜杠开头).当您使用BuildAction资源时,您可以访问图像为"/YearBook;component/Resources/Images/darkaurora.png"(程序集名称;组件/相对路径).希望这会有所帮助.

  • "嵌入式资源"和"资源"是不同的.如果您在Reflector或ILSpy中查看生成的程序集,您将看到它们以不同的方式包含在内.作者询问如何使用"嵌入式资源"而不是"资源". (20认同)
  • 当BuildAction为Resource时,您需要在程序集名称上使用前导斜杠:"/ YearBook; component ....".请参见http://stackoverflow.com/questions/347614/wpf-image-resources (5认同)
  • 在资源作为BuildAction的情况下,我认为它应该是"pack:// application:,,,/Resources/Images/darkaurora.png" (2认同)