Search code examples
c#visual-studioimagexamlruntime

How to show an image on a XAML?


First I thought I needed to work with BorderBrushes, ImageSources, etc., but then I found out that a simple Image in a simple Border seems to be enough, as you can see in this answer.

This is the reason I thought that (screenshot of the design):

enter image description here

(The first one comes from the file "All_Colours.png" and the third from "Transparant.png", I don't care about the second brown square)

In XAML, it looks as follows:

<Border x:Name="box_Interior_Group_Color">
  <Image Source="/Company.Customer.Client;component/Views/views/All_Colours.png"/>
</Border>

...

<Border x:Name="box_Interior_Transparant">
  <Image Source="/Company.Customer.Client;component/Views/views/Transparant.png"/>
</Border>

... but when I run this, this is what I see:

enter image description here

You might think "you need to copy the files "All_Colours.png" and "Transparant.png" to your runtime directory", but that's the point:

  • I have copied those files to the runtime directory and to the "Modules" directory (I'm working on a DLL, located in a "Modules" subdirectory of the runtime directory), but that didn't save the issue.
  • There is nothing in the output window. I can imagine that Visual Studio wants to show those *.png files and fails, but in that case it must show some information in the output window.

What can I do?

Extra information: when I start the "Select Element" feature in the debugger, I am able to select the brown square, but the others look not even to be present on the XAML:

Hovering over the brown one (the brown gets slightly grayed):

enter image description here

Hovering over another one (everything looks slightly grayed, it's like those other borders are not even present):

enter image description here

When I open the "Live Visual Tree" feature and I select the mentioned boxes, they do appear, as you can see in following screenshots:

enter image description here and enter image description here


Solution

  • The syntax Source="/Company.Customer.Client;component/Views/views/All_Colours.png" means that the image is expected to be compiled as Resource into the Company.Customer.Client assembly. So the image files need not be in the runtime directory, but this assembly is containing the images.

    When adding an image file to the project Company.Customer.Client, make sure that the build action is set to "Resource".

    enter image description here