0

I just saw an educational video that explained how to show an image in a window by using the <Image>-tag in XAML. The author explained that you just have to put the path of the image there, in his case it was

C:\Users\BOFH\CSharpProjects\SomeEmployer\MyProject3\myImage.png

(ok, actually the path was a bit different, and he is not the BOFH, but I don't want to tell the name of that author here.)

What bothers me is that there is an absolute path. When I work in a team of developers, I really cannot use an absolute path and commit and push my change to our GIT repository.

In Xcode I just add an image to a project, and it just works. Is there a similar workflow when developing with Visual Studio?


EDIT: Problem solved. I read this SO question as suggested by @nosale in the comments and it solved it. I think the reason why I didn't find the solution myself at first, is that there are so many developers who are doing it wrong. Like either hardcoding the paths, or putting the files into bin/Debug, or using some environment variable like RESOURCE_PATH and dynamically resolve that at runtime. All these solutions are awful in my opinion.

Michael
  • 6,451
  • 5
  • 31
  • 53
  • See https://stackoverflow.com/questions/25714085/wpf-import-image-as-resource – nosale Nov 30 '18 at 22:31
  • @nosale: thanks, it worked! – Michael Nov 30 '18 at 22:40
  • For further and more detailed information https://learn.microsoft.com/en-US/dotnet/framework/wpf/app-development/wpf-application-resource-content-and-data-files and https://learn.microsoft.com/en-US/dotnet/framework/wpf/app-development/pack-uris-in-wpf – nosale Nov 30 '18 at 22:40

1 Answers1

0

The closest to "add to a project and it just works" you would get to would be to right click the file you included and choose "copy Always" or "copy if newer" depending on your use case, that would copy the file to the bin directory on compile with the same relative path as it has in the project.

So if your file is at the root of the project and named hello.txt you could simply refer to it by it's name.

In the case of XAML you could also embed it as a ressource and directly refer to that using the appropriate source format, for exemple if you have a file named hello.jpg at the root of your project you could refer to it as

ImageSource="pack://application:,,,/Resources/hello.jpg"
Ronan Thibaudau
  • 3,413
  • 3
  • 29
  • 78