在 .NET Core 中使用 System.Windows

izl*_*lin 7 c# .net-core visual-studio-2019 .net-core-3.1

我在 Visual Studio 2019 中有一个项目,正在从 .NET Framework 4.6 迁移到 .NET Core 3.1。

我使用 Microsoft 的指南来移植我的项目,如下所述。我运行了可移植性分析器,它表明该项目是 100% 可移植的。

但对 System.Windows 的所有依赖都不再起作用。例如我使用System.Windows.Rect. 在官方文档中明确指出它可用于.NET Core 3.1。

然而,在代码中,它用“无法找到类型或命名空间名称‘Rect’(您是否缺少 using 指令或程序集引用?)”标记 Rect,并在顶部用消息“ using System.WindowsUsing 指令是”标记我的灰色。不必要”。

此错误适用于我的代码中的许多内容,例如System.Windows.ResourceDictionary, System.Windows.Application.Current, System.Windows.Point, ...

因此,由于某些原因,我似乎无法使用System.Windows,即使使用本身似乎工作正常。

System.Windows我在 NuGet 包管理器中搜索并用谷歌搜索,但找不到任何东西。

所以这是我的问题:如何System.Windows在 Visual Studio 2019 的 .NET Core 3.1 项目中使用?我目前的猜测是,我需要手动包含该程序集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,而且它似乎不是正确的。

Dan*_*con 13

以下是如何做到这一点net5.0

 <PropertyGroup>
    <TargetFramework>net5.0-windows</TargetFramework>
    <UseWPF>true</UseWPF>
  </PropertyGroup>
Run Code Online (Sandbox Code Playgroud)

  • `-windows` 是关键!谢谢 (2认同)

Jac*_*SFT 2

根据您的描述,您希望在 .NET Core 3.1 中使用 System.Windows.Rect

使用 Visual Studio 2019 进行项目。我找到了解决方案,您可以尝试以下步骤。

首先,我们需要创建一个 .net core 3.1 控制台应用程序。

其次,我们需要UseWPF=true在 中设置属性csproj file

 <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
         <UseWPF>true</UseWPF>
  </PropertyGroup>
Run Code Online (Sandbox Code Playgroud)

第三,我们需要安装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;

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,如果你想system.windows在.net core 3.1中使用,我建议你使用WPF

.net 核心 3.1 应用程序。