使用 NuGet 将功能添加到应用

已完成

NuGet 和包

开发人员通过将其工作捆绑到包中来共享库和资源。 可以将包拉取到 Visual Studio,为项目提供额外的功能。 例如,添加对 JSON 的支持,或向 XAML 添加动画例程。

NuGet 是适用于 .NET、UWP、Windows 窗体和 WPF 项目的包管理器。 使用 NuGet 浏览包目录以在项目中安装、更新或删除包。 NuGet 内置于 Visual Studio 中,因此,无需离开 IDE。

安装 NuGet 包

让我们使用 NuGet 从 Win2D 包安装新的 XAML 动画功能:

  1. 选择“项目”,然后选择“管理 NuGet 包”

    Screenshot of the project menu in Visual Studio. The project menu option and manage NuGet packages option are highlighted.

  2. 选择“浏览”,在搜索框中键入“Win2D”,然后按 Enter。 随即显示可用包的列表。

    Screenshot of the NuGet package manager within Visual Studio. The search bar (and relevant package) are highlighted.

  3. 从列表中选择“Win2D.uwp”并选择“安装”按钮。 包随即开始安装。

    Screenshot of the NuGet package manager within Visual Studio. The win2D.uwp package is highlighted along with the install button.

    安装包后,可以直接在 XAML 代码中调用一个功能来定义主页。

    注意

    如果在安装过程中遇到错误,则可能是未设置正确的最低版本。

    选择“项目”,然后选择“Hello World 属性”。 将“最低版本”更改为“Windows 10,版本 1809”或更高版本

  4. 此时会显示“预览更改”窗口。 选择“确定”

    Screenshot of the preview changes window in Visual Studio. The OK button is highlighted.

  5. 此时会显示“接受许可证”窗口。 若要同意许可条款,请选择“我接受”

    Screenshot of the license acceptance window in Visual Studio. The I accept button is highlighted.

  6. 在解决方案资源管理器中,双击“MainPage.xaml”,在设计视图中将其打开

    Screenshot of the Visual Studio solution explorer. The MainPage.xaml file is highlighted.

  7. 使用“箭头”按钮展开编辑视图

    Screenshot of Visual Studio in design view. The switch views (arrows icon) button is highlighted.

  8. 将 MainPage.xaml 中的所有 XAML 代码替换为以下代码

    <Page
        x:Class="Hello_World.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
        xmlns:canvas="using:Microsoft.Graphics.Canvas.UI.Xaml">
        <Grid>
            <canvas:CanvasControl Draw="CanvasControl_Draw" ClearColor="CornflowerBlue"/>
        </Grid>
    </Page>
    
  9. 将 MainPage.xaml.cs 中的所有 C# 代码替换为以下代码

    using Windows.UI;
    using Windows.UI.Xaml.Controls;
    using Microsoft.Graphics.Canvas.UI.Xaml;
    
    namespace Hello_World
    {
        public sealed partial class MainPage : Page
        {
            public MainPage()
            {
                this.InitializeComponent();
            }
    
            void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
            {
                args.DrawingSession.DrawEllipse(155, 115, 80, 30, Colors.White, 3);
                args.DrawingSession.DrawText("Hello world!", 100, 100, Colors.White);
            }
        }
    }
    
    

    此 XAML 代码包含对之前安装的包的引用。

  10. 运行程序以查看结果。

    Screenshot showing the Visual Studio menu bar. The run button, represented by a green triangle, is highlighted.

    应会看到一个椭圆形,在蓝色背景上环绕着文本“Hello World!”。

    Screenshot of the running Hello World app built in this unit. The debug toolbar is also shown.