将图像添加到 C# WPF .NetCore WPF 应用程序时遇到问题 [英] Trouble adding images to C# WPF .NetCore WPF application

查看:30
本文介绍了将图像添加到 C# WPF .NetCore WPF 应用程序时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了练习,我想向 WPF .NetCore 应用程序的 UI 添加图像.为此,我在 XAML 中使用了以下代码.

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"/>

通常,代码应该在执行应用程序时在 UI 中显示我的图像,但不知何故 UI 保持为空.对我来说,令人惊讶的是,VS 的图形 XAML 编辑器显示图像.

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.

我也对 .Net Framework 进行了同样的尝试,这里一切正常.我还检查了案例,该图像未声明为资源,但这并不是我的解决方案.

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.

推荐答案

这个问题的解决方案是检查项目文件,以.csproj结尾.如下所示.

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.

这篇关于将图像添加到 C# WPF .NetCore WPF 应用程序时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆