使用System.Windows在.NET Core中

6
我在Visual Studio 2019中有一个项目,我正在将其从.NET Framework 4.6迁移到.NET Core 3.1。
我使用了Microsoft的指南来移植我的项目,在此处描述。我运行了Portability Analyzer,它显示该项目可完全移植。
但是,所有对System.Windows的依赖都不再起作用。例如,我使用System.Windows.Rect。在官方文档中,它明确说明适用于.NET Core 3.1。
然而,在代码中,它用"The type or namespace name 'Rect' could not be found(are you missing a using directive or an assembly reference?)"标记Rect,并在顶部用"Using directive is unnecessary"的消息将我的using System.Windows标记为灰色。
这个错误适用于我代码中的许多东西,比如 System.Windows.ResourceDictionarySystem.Windows.Application.CurrentSystem.Windows.Point 等等。
因此,出于某些原因,似乎我无法使用 System.Windows,即使使用本身似乎运行良好。
我在 NuGet 包管理器和 Google 中搜索了 System.Windows,但没有找到任何内容。
所以我的问题是:如何在 Visual Studio 2019 的 .NET Core 3.1 项目中使用 System.Windows? 我目前的猜测是,我需要手动包含程序集 WindowsBase.dll,但在我的安装目录(C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional)中,我只能在 C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\Extensions\Microsoft\LiveShare\Agent 找到一个,看起来并不是正确的。

1
在你的.proj文件中,你是使用<Project Sdk="Microsoft.NET.Sdk">还是<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> - Rosdi Kasim
你在 csproj 文件中设置了 UseWPF=true 属性吗? - Pavel Anikhouski
1
@PavelAnikhouski 我还没有在我的csproj文件中设置UseWPF,所以它仍然是默认值。 - izlin
2
就图形点和矩形而言,微软已经发布了System.Drawing.Common以跨平台提供对GDI+图形功能的访问。您可以通过NuGet安装System.Drawing.Common。请检查是否已安装该库。 - Goodies
这个回答解决了你的问题吗?如何在.NET Core 3.0中为WPF应用程序引用System.Windows.Forms? - JumpingJezza
显示剩余2条评论
2个回答

10

以下是使用net5.0实现的方法:

 <PropertyGroup>
    <TargetFramework>net5.0-windows</TargetFramework>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

2
“-windows” 是关键!谢谢。 - Tea

2
根据您的描述,您想在使用Visual Studio 2019的.NET Core 3.1项目中使用System.Windows.Rect。我找到了一个解决方案,您可以尝试以下步骤。
首先,我们需要创建一个.NET Core 3.1控制台应用程序。
其次,我们需要在csproj文件中设置UseWPF=true属性。
 <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
         <UseWPF>true</UseWPF>
  </PropertyGroup>

第三步,我们需要安装NuGet包System.Runtime.WindowsRuntime

第四步,重新构建应用程序并编写以下代码。

using Windows.Foundation;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Rect myRect1 = new Rect();
            myRect1.X = 10;
            myRect1.Y = 100;
            myRect1.Width = 150;
            myRect1.Height = 100;

        }
    }
}

此外,如果您想在 .net core 3.1 中使用 system.windows,我建议您使用 WPF
.net core 3.1 应用程序。

这种方法不被你的雇主微软所推荐。正确的做法是通过运行 dotnet new wpf 创建一个 WPF .NET Core 项目。 - Lex Li

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接