ImageSource from a relative resource

00jt picture 00jt · Sep 28, 2012 · Viewed 25.5k times · Source

I'm trying to use a local resource to put an icon inside a Button. (C# Visual Studio 2012)

Directly inside my project i have a folder called "Resources" which contains "Icons/MyIcon.png"

The following code works (but is not using a relative path)

<Button Width="20" Height="20">
  <Button.Background>
        <ImageBrush ImageSource="C:\Documents\MyProject\Resources\Icons\MyIcon.png">
          </ImageBrush>
      </Button.Background>

However, i want it to use a relative path... so i tried the following

  <ImageBrush ImageSource="..\MyProject\Resources\Icons\MyIcon.png">

It compiles, but then gives me the error:

{"Cannot locate resource 'myproject/resources/icons/myicon.png'."}

Then i found an article that talked about referencing the project and said to do:

"/[ assembly name ];component[ path within the project ]"

so i tried that:

<ImageBrush ImageSource="/MyProject;component\Resources\Icons\MyIcon.png">

But it doesn't work.

It DOES show up in the GUI-Builder... but when i actually try to "debug" the code... it fails to run.

If i change the path at all by adding '123' for example:

 <ImageBrush ImageSource="/MyProject;component\Resources\Icons\MyIcon123.png">

i get a pre-compile error: "cannot find the file specified". Once i remove the '123' the error goes away. And the icon again is displayed in the Form. But when i run... i still get:

{"Cannot locate resource 'resources/icons/myicon.png'."}

What is going on? Why can it only find the resource BEFORE it runs? and not when i actually start?

Answer

Eric Olsson picture Eric Olsson · Sep 28, 2012

Do you need to set the BuildAction of the image to Resource? Is it being built into the assembly? Or are you treating it like Content? In that case, you'd want to set the BuildAction to Content and set CopyToOutputDirectory appropriately.

Here's a link to an MSDN article treating Resources, Content files, etc.