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

Jam*_* Ko 10 .net c# asp.net windows-runtime asp.net-core

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

project.json

{
    "frameworks": {
        "net46": {
            "frameworkAssemblies": {
                "WindowsBase": "4.0.0.0"
            }
        },
        "netcore50": {
            "dependencies": {
                "Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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....
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然这可以很好地编译net46(这是传统的.NET Framework),但我无法使其工作netcore50(可以由Windows 10应用程序使用).出于某种原因,它看起来像类型DependencyPropertyDependencyObject不包含在该配置中.

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

谢谢你的帮助.


编辑:我刚刚输入DependencyPropertyVS并点击F12.看起来该类型存在于Windows.Foundation.UniversalApiContract程序集中,但NuGet上没有这样的程序包.

Jam*_* Ko 6

终于解决了我自己的问题!(如果您正在寻找快速回答,可能需要向下滚动.)

我记得.NET Core GitHub repo有一堆特定于WinRT的库,比如说System.Runtime.WindowsRuntime.所以,我去那里看看他们是怎么做到的.

它们似乎使用某种内部托管的"目标包",它包含一个Windows.winmd文件(它包含Windows运行时中的所有类型),以实现这种效果.不幸的是,该软件包托管在仅供.NET Core团队使用的私有NuGet feed上,因此我无法使用它.

我已经打开这个问题上CoreFX回购在这里,所以我可以申请微软对这一问题的官方的解决方案.与此同时,我已经掌握了自己的事情.我在Windows.winmd笔记本电脑上找到了所有不同的版本,并将它们作为NuGet包上传.他们来了:

您可以像这样使用它们:

"frameworks": {
    ".NETPortable,Version=v4.5,Profile=Profile32": {
        "dependencies": {
            "Target.WindowsRuntime": "8.1.2"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在那之后,你将能够写出这样的东西:

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

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

它会起作用.


Men*_*ndy 6

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