如何在 .NET Core 库中使用 Windows 运行时 类?

How to use Windows Runtime classes in .NET Core libraries?

我正在开发一个用于 WPF 和 Windows 10 的库。我 运行 遇到了让它在后者上编译的问题。这是一些代码:

project.json

{
    "frameworks": {
        "net46": {
            "frameworkAssemblies": {
                "WindowsBase": "4.0.0.0"
            }
        },
        "netcore50": {
            "dependencies": {
                "Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0"
            }
        }
    }
}

Dependency.cs

using System;
using System.Collections.Generic;
#if NET46
using System.Windows; // .NET Framework 4.6
#elif NETCORE50
using Windows.UI.Xaml; // Windows 10 apps
#endif

public static class Dependency
{
    public static DependencyProperty Register<T, TOwner>(string name, PropertyChangedCallback<T, TOwner> callback)
        where TOwner : DependencyObject
    {
        // Code here....
    }
}

虽然这对 net46(这是传统的 .NET Framework)编译得很好,但我很难让它为 netcore50(可以被 [=46= 使用)工作] 10 个应用程序)。出于某种原因,该配置中似乎未包含 DependencyPropertyDependencyObject 等类型。

是否有我可以安装的包含这些类型的 netcore50 兼容 NuGet 包,以便我可以从我的库中使用它们?

感谢您的帮助。


编辑: 我刚在 VS 中输入 DependencyProperty 并按 F12。该类型似乎位于 Windows.Foundation.UniversalApiContract 程序集中,但 NuGet 上没有此类包。

WPF 不兼容 .net Core 也不兼容 W10 通用应用程序,据我所知,目前只有控制台应用程序和 Web 应用程序与 .net Core 兼容,您应该仍然可以使用新的代码库新项目系统,但您需要从配置中删除 .net 核心才能编译 如果您想将 .net core 与 linux 与桌面应用程序一起使用,您只需等待,或使用兼容的窗口应用程序框架(如果有的话),您应该能够使用跨平台框架以 html/js 为基础,例如 Electron 或 Cordova(不确定是否有 Cordova 桌面应用程序框架)

终于靠自己解决了! (如果您正在寻找快速答案,您可能需要向下滚动。)

我偶然想起 .NET Core GitHub repo 有一堆特定于 WinRT 的库,例如 System.Runtime.WindowsRuntime。所以,我就去那里看看他们是怎么做到的。

他们似乎使用某种内部托管的 "targeting pack",其中包含一个 Windows.winmd 文件(其中包含 Windows 运行时中的所有类型),以实现此目的影响。不幸的是,该包托管在仅供 .NET Core 团队使用的私有 NuGet 提要上,因此我无法使用它。

我已经在 CoreFX 存储库 here 上提出了一个关于此的问题,因此我可以向 Microsoft 请求官方解决此问题。与此同时,我已经把事情掌握在自己手中。我在笔记本电脑上找到了 Windows.winmd 的所有不同版本,并将它们作为 NuGet 包上传。他们在这里:

您可以像这样使用它们:

"frameworks": {
    ".NETPortable,Version=v4.5,Profile=Profile32": {
        "dependencies": {
            "Target.WindowsRuntime": "8.1.2"
        }
    }
}

之后,您将能够编写如下内容:

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

public class MyApp : Application
{
    public MyApp()
    {
        var button = new Button();
        button.Content = "Hello, world!";
    }
}

它会正常工作。

对于 .NET Core 3 及更高版本(现在为预览版),您可以安装一个包含大多数 WinRT 的软件包 类 Microsoft.Windows.SDK.Contracts