Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble adding images to C# WPF .NetCore WPF application

Tags:

c#

.net-core

wpf

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.

like image 814
lpsweder Avatar asked Sep 18 '25 19:09

lpsweder


2 Answers

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.

like image 67
lpsweder Avatar answered Sep 21 '25 13:09

lpsweder


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.

like image 34
Zath Avatar answered Sep 21 '25 12:09

Zath