来自相对资源的ImageSource

00j*_*0jt 8 c# wpf xaml imagesource visual-studio-2012

我正在尝试使用本地资源在Button中放置一个图标.(C#Visual Studio 2012)

直接在我的项目中,我有一个名为"Resources"的文件夹,其中包含"Icons/MyIcon.png"

以下代码有效(但不使用相对路径)

<Button Width="20" Height="20">
  <Button.Background>
        <ImageBrush ImageSource="C:\Documents\MyProject\Resources\Icons\MyIcon.png">
          </ImageBrush>
      </Button.Background>
Run Code Online (Sandbox Code Playgroud)

但是,我希望它使用相对路径...所以我尝试了以下

  <ImageBrush ImageSource="..\MyProject\Resources\Icons\MyIcon.png">
Run Code Online (Sandbox Code Playgroud)

它编译,但然后给我错误:

{"Cannot locate resource 'myproject/resources/icons/myicon.png'."}
Run Code Online (Sandbox Code Playgroud)

然后我发现了一篇文章,谈到引用该项目,并说:

"/[ assembly name ];component[ path within the project ]"
Run Code Online (Sandbox Code Playgroud)

所以我试过了:

<ImageBrush ImageSource="/MyProject;component\Resources\Icons\MyIcon.png">
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

它会出现在GUI-Builder中...但是当我真正尝试"调试"代码时......它无法运行.

如果我通过添加'123'来改变路径,例如:

 <ImageBrush ImageSource="/MyProject;component\Resources\Icons\MyIcon123.png">
Run Code Online (Sandbox Code Playgroud)

我得到一个预编译错误:"找不到指定的文件".一旦我删除'123',错误就会消失.并再次在图表中显示图标.但当我跑...我仍然得到:

{"Cannot locate resource 'resources/icons/myicon.png'."}
Run Code Online (Sandbox Code Playgroud)

到底是怎么回事?为什么它只能在运行之前找到资源?而不是当我真正开始?

Eri*_*son 8

您是否需要将图像的BuildAction设置为Resource?它被装入集会吗?或者你像内容一样对待它?在这种情况下,您需要将BuildAction设置为Content并相应地设置CopyToOutputDirectory.

这是一篇关于处理资源,内容文件等的MSDN文章的链接.


小智 6

我知道这是一个老帖子但是对于VS2013这些例子都不适用于我,但所有这些例子的组合是我现在必须在URI中引用我的图像资源和来源.

"pack://application:,,,/!APP NAME!;component/Resources/Purple.bmp"
Run Code Online (Sandbox Code Playgroud)

当然替代!APP NAME!你的.."pack://application:,,,/test1;component/Resources/Purple.bmp"