With the intention of exercising I wanted to add an image to the UI of an WPF .NetCore application. In order to do this I use the following code in my XAML.
<Image Source="images/myimage.png" Height="100" Width="100" Margin="20,20,0,0"/>
Normally the code should display my image in the UI while executing the application, but somehow the UI stays empty. For me it was surprising, that the graphical XAML editor of VS shows the image.
I also tried the same with the .Net Framework and here everything worked well. As well I checked the case, that the image is not declared as resource, but this didn't was a solution in my case.
The solution for this problem was to check the project file, ending with .csproj
. This looked like the following.
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
</Project>
As you can see, the declaration for the image is still missing. So you have to add the following lines to the code above.
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<Resource Include="images/myimage.png" />
</ItemGroup>
</Project>
Please note that this post is a replication of an older post by me. It's a solution for me, so I don't belive that this is the best practice. I think it's may be helpful for others. That's the reasen why I post it a secound time.
You have to make sure when adding the image to the project, the Build Action property for that image file is set to Resource
. By default it will be set to None
.
This is different from .NET Framework projects, where the default for image files already is Resource
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With