1

I have an image file in a shared project. It is the company logo.

In the shared project it is in Resources/logo.png.

Its Build Action is "Content".

Copy to Output Directory is set to "Copy always"

When I use the XAML editor, it appears. When I run it via the debugger, it does not appear. When I build the solution and install the software, it does not appear.

However, I see the file in the install in the /Resource directory as logo.png.

I've tried the following XAML:

<Image Source="Resource/logo.png"/>
<Image Source="/Resource/logo.png"/>
<Image Source="./Resource/logo.png"/>
<Image Source="pack://application:,,,/Resource/logo.png"/>

None of the variations worked.

However, if I use the following in the code behind

string path = Path.Combine(Environment.CurrentDirectory, "Resource", "logo.png");
Uri uri = new Uri(path);
Logo.Source = new BitmapImage(uri);

with the XAML

<Image x:Name="Logo"/>

It works; however, using Environment.CurrentDirectory may not always work.

What is the proper way to reference the image file in XAML?

zekim
  • 82
  • 4
  • You can copy by using Build Event (Post build): del "$(ProjectDir)$(OutDir)img\*.png" xcopy "$(ProjectDir)img\*" "$(ProjectDir)$(OutDir)img" – Đăng Khôi May 31 '22 at 00:35
  • Use Build Action **Resource** and add the name of the assembly that contains the image resource to the Pack URI: `pack://application:,,,/AssemblyName;component/Resource/logo.png`. – Clemens May 31 '22 at 04:52
  • Are you really asking about a [shared project](https://stackoverflow.com/q/30634753/1136211), or a shared library project? – Clemens May 31 '22 at 08:37

1 Answers1

1

In the project which uses the image file, create "Resources" folder and add the image file by Add As Link. Set its Build Action to Resource. Then pack URI should work.

<Image Source="pack://application:,,,/Resources/logo.jpg"/>

I tested the above in VS2022 but it would be the same in VS2019.

EDIT

Pack URI is a common technique in WPF and the point is that it is still valid in the case of a file linked from Shared project.

emoacht
  • 2,764
  • 1
  • 13
  • 24
  • This would duplicate the resource. Both assemblies, the library and the application that references the library would embed the same image file. This is definitely *not* how it should be done. – Clemens May 31 '22 at 06:38
  • @Clemens I understand OP is talking about Shared project. Unlike ordinary library project, it does not produce its own assembly. Its content is merely used for building the assembly of other project which refers that Shared project. So there would be no duplication. – emoacht May 31 '22 at 08:15
  • That may be, although they may also just be confusing the terms project and library, which happens quite often. – Clemens May 31 '22 at 08:33