Reputation: 82
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?
Upvotes: 1
Views: 858
Reputation: 3556
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.
Upvotes: 1