将 UWP 应用迁移到 WinUI 3

UWP 不再处于积极开发状态。 WinUI 3 和 Windows 应用 SDK 是其继任者,AI 工具可以自动执行大部分迁移。 主要挑战是,AI 模型是在多年的 UWP 示例上训练的,因此没有指导,它们会重现你试图摆脱的模式。 此页面为您的代理提供其正确完成任务所需的上下文。

安装 WinUI 代理插件

技能 winui-uwp-migration 会自动处理常见替换:

gh copilot plugin install winui@awesome-copilot

有关完整详细信息,请参阅 WinUI 代理插件 。

API 替换表

下表汇总了最常见的 API 替换。 有关完整的详细映射(包括成员、属性和不太常见的 API),请参阅将 UWP API 和库映射到Windows 应用 SDK。

Important

x:Bind 默认为 OneTime 模式。 与 {Binding}(其默认值为 OneWay)不同,x:Bind 只会求值一次,除非你指定 Mode=OneWay 或 Mode=TwoWay。 在迁移过程中,审核绑定到运行时更改的属性的所有 x:Bind 表达式 , 缺少 Mode=OneWay 会导致编译时不可见的“UI 不会更新”bug。

Namespaces

UWP WinUI 3
Windows.UI.Xaml.* Microsoft.UI.Xaml.*
Windows.UI.Xaml.Controls.* Microsoft.UI.Xaml.Controls.*
Windows.UI.Xaml.Media.* Microsoft.UI.Xaml.Media.*
Windows.UI.Composition Microsoft.UI.Composition

线程处理

UWP WinUI 3
CoreDispatcher DispatcherQueue
Dispatcher.RunAsync(...) DispatcherQueue.TryEnqueue(...)
CoreApplication.MainView.CoreWindow.Dispatcher this.DispatcherQueue(来自 Window 或 Page)

Windowing

UWP WinUI 3
ApplicationView AppWindow
ApplicationView.GetForCurrentView() AppWindow.GetFromWindowId(...)
ApplicationViewTitleBar AppWindowTitleBar
CoreWindow Microsoft.UI.Xaml.Window
SystemNavigationManager 通过AppWindowTitleBar返回按钮

对话框和选择器

UWP WinUI 3
MessageDialog ContentDialog(设置 XamlRoot)
FileOpenPicker FileOpenPicker + InitializeWithWindow
FileSavePicker FileSavePicker + InitializeWithWindow
FolderPicker FolderPicker + InitializeWithWindow

Important

选取器在调用InitializeWithWindow之前需要PickSingleFileAsync(或类似):

var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow);
WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd);

ContentDialog 需要 XamlRoot (不是 InitializeWithWindow):

var dialog = new ContentDialog { XamlRoot = this.Content.XamlRoot, ... };
await dialog.ShowAsync();

Notifications

UWP WinUI 3
Windows.UI.Notifications.ToastNotificationManager Microsoft.Windows.AppNotifications.AppNotificationManager
Windows.UI.Notifications.BadgeUpdateManager Microsoft.Windows.BadgeNotifications.BadgeNotificationManager
Windows.UI.Notifications.TileUpdateManager 磁贴已弃用——请使用通知或小部件

网络和 HTTP

UWP WinUI 3 (建议)
Windows.Web.Http.HttpClient System.Net.Http.HttpClient (可移植,无 WinRT 依赖项)
Windows.Web.Syndication.SyndicationClient System.ServiceModel.Syndication.SyndicationFeed + HttpClient
Windows.Web.AtomPub.AtomPubClient System.ServiceModel.Syndication 或直接通过 HTTP

注释

WinRT HTTP API(Windows.Web.Http)仍适用于打包的 WinUI 3 应用,但建议使用.NET等效项来实现可移植性、更简单的调试和更广泛的生态系统支持(中间件、DI、模拟)。

UWP WinUI 3
Frame.Navigate(typeof(MyPage)) Frame.Navigate(typeof(MyPage)) — 未更改
SystemNavigationManager.BackRequested 通过 NavigationView 或 AppWindow 处理
Windows.UI.Core.Preview.SystemNavigationManagerPreview AppWindow.Closing 事件

注释

自定义汉堡导航(SplitView + NavMenuListView): 许多 UWP 示例使用自定义 AppShell.xaml、SplitView 以及手写的 NavMenuListView 控件(约 500 多行)来实现导航。 在 WinUI 3 中,将此整个模式替换为 NavigationView,该模式提供与内置辅助功能、响应行为和后退按钮支持相同的 UX。 这通常意味着代码量可减少 80%。

MVVM 模式

UWP (常见自定义实现) WinUI 3 (建议)
自 定义 BindableBase / ObservableObject CommunityToolkit.Mvvm.ComponentModel.ObservableObject
自 定义 DelegateCommand / RelayCommand CommunityToolkit.Mvvm.Input.RelayCommand
手动 SetProperty + OnPropertyChanged [ObservableProperty] 源生成器
自定义 INavigationService 内置 Frame.Navigate + NavigationView

Tip

CommunityToolkit.Mvvm NuGet 包是适用于 WinUI 3 应用的推荐 MVVM 基础库。 它用经过验证、由源代码生成的等效实现取代手写的基类,从而省去数百行样板代码。

dotnet add package CommunityToolkit.Mvvm

应用生命周期

UWP WinUI 3
Application.Current.Suspending Microsoft.Windows.AppLifecycle(需要体系结构更改 - 请参阅注释)
Application.Current.Resuming AppInstance.GetCurrent().Activated (请参阅注释)
BackgroundTaskBuilder Windows 应用 SDK后台任务

注释

WinUI 3 应用生命周期迁移不是简单的 API 名称交换。 Windows 应用 SDK 使用不同的激活和暂停模型。 将生命周期代码视为需要专用重写,而不是自动替换。 有关完整模型,请参阅 Windows 应用 SDK 生命周期文档。

设置和存储

UWP WinUI 3 (打包) WinUI 3 (未打包)
ApplicationData.Current.LocalSettings 不变 ❌ 引发 — 没有包标识
ApplicationData.Current.LocalFolder 不变 ❌ 引发 — 没有包标识
Windows.Storage.KnownFolders 不变 ❌ 引发 — 没有包标识

Warning

未打包的应用 无法使用 ApplicationData.Current — 它在运行时引发,因为没有包标识。 请改用标准.NET文件 API:

var appData = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
    "YourAppName");
Directory.CreateDirectory(appData);
var json = JsonSerializer.Serialize(data);
await File.WriteAllTextAsync(Path.Combine(appData, "settings.json"), json);

注释

如果你的 UWP 应用使用了 DataContractSerializer 以及 [DataMember]/[IgnoreDataMember],请考虑迁移到 System.Text.Json(速度更快、体积更小,并且支持源代码生成)。 属性映射为:

  • [DataMember] [JsonPropertyName("name")] →(或直接使用属性名称)
  • [IgnoreDataMember] → [JsonIgnore]
  • [DataContract] →不需要等效属性(默认情况下 System.Text.Json 序列化公共属性)

不更改的 API

Windows.Devices.*、Windows.Media.*、Windows.UI.ViewManagement.UISettings、Windows.UI.Color,并且 XAML 命名空间外部的大多数 WinRT API 保持不变。

没有直接等效项的控件

WinUI 3 中不存在某些 UWP 控件。 根据方案选择替换项:

UWP 控件 WinUI 3 替代方案 备注
Pivot TabView、 NavigationView (顶部模式)或 RadioButtons + 可见性 对于 2–3 个固定选项卡,使用 RadioButtons 进行可见性切换是最简单的。 对于动态/可关闭选项卡,请使用 TabView。
RadialController WinRT 与窗口句柄互操作 RadialController.CreateForCurrentView() 没有直接等效项。 将 RadialControllerInterop 与 GetForWindow(hwnd) 结合使用。
SystemNavigationManager 自定义后退按钮或 NavigationView.IsBackEnabled SystemNavigationManager.GetForCurrentView() 不存在。 添加自己的后退按钮或使用 NavigationView“内置后退”按钮。

墨迹、Win2D 和打印

这些子系统需要命名空间更改以外的特定迁移步骤。

Windows Ink

WinUI 在Windows 应用 SDK的实验版本中包括InkCanvasInkToolbar和InkPresenter作为实验 API。 稳定版本不包含它们。 有关设置、工具栏自定义和已知限制,请参阅 WinUI 应用的墨迹书写控件。

在实验版本中,处理墨迹输入的控件和类型位于 Microsoft.UI.Xaml.Controls 中。 笔划和绘图属性保持不变 Windows.UI.Input.Inking:

UWP WinUI 3(实验性版本)
Windows.UI.Xaml.Controls.InkCanvas、InkToolbar和其他InkToolbar*类型 Microsoft.UI.Xaml.Controls,相同的类型名称。 某些成员存在差异。
Windows.UI.Input.Inking.InkPresenter、InkStrokeContainer、InkStrokeInput、InkUnprocessedInput、InkSynchronizer、InkInputConfiguration、InkInputProcessingConfiguration、InkInputProcessingMode、InkInputRightDragAction、InkHighContrastAdjustment、InkStrokesCollectedEventArgs、InkStrokesErasedEventArgs Microsoft.UI.Xaml.Controls,类型名称相同。 某些成员存在差异。
Windows.UI.Input.Inking.InkStroke、InkDrawingAttributes、InkPoint、InkStrokeBuilder、InkPersistenceFormat、PenTipShape 无更改
Windows.UI.Core.CoreInputDeviceTypes 无更改

前两行中的每个 UWP 类型都有一个具有相同名称的对应项,但Windows 应用 SDK 2.5.4 实验版不包含其所有成员:

  • InkStrokeContainer 没有公共构造函数,并且 InkPresenter.StrokeContainer 是只读的。 若要在笔划集之间切换,请使用 SaveAsync 保存每组,再使用 LoadAsync 恢复,这将替换当前笔划。
  • SaveAsync 并 LoadAsync 返回 IAsyncAction,因此它们不会报告进度,并且 SaveAsync 不返回写入的字节数。
  • InkStrokeContainer.GetRecognitionResults、 InkStrokeContainer.UpdateRecognitionResults和 InkInputConfiguration.IsPenHapticFeedbackEnabled 不可用。
  • InkToolbarRulerButton.Ruler和InkToolbar.IsRulerButtonCheckedChanged事件不可用。 UWP 已弃用 InkToolbarRulerButton,改用 InkToolbarStencilButton,因此请改用模具按钮和 InkToolbar.IsStencilButtonCheckedChanged 事件。

Windows 应用 SDK 2.4.1-experimental 添加了橡皮擦 API,例如 InkToolbarEraserKind 和 InkToolbarEraserButton.SelectedEraser,而 2.5.4-experimental 删除了这些 API。 它们从来不是 UWP 的一部分,因此不要将它们添加到迁移后的代码中。 有关完整列表,请参阅 自 2.4.1-experimental 以来的更改。

由于这两个命名空间中都存在诸如 InkPresenter 和 InkStrokeContainer 之类的类型,因此导入 Microsoft.UI.Xaml.Controls 和 Windows.UI.Input.Inking 会在使用这些名称时导致错误 CS0104。 导入 Microsoft.UI.Xaml.Controls,并为所使用的 Windows.UI.Input.Inking 类型添加别名指令:

using Microsoft.UI.Xaml.Controls;
using InkDrawingAttributes = Windows.UI.Input.Inking.InkDrawingAttributes;
using InkStroke = Windows.UI.Input.Inking.InkStroke;

InkStrokeContainer.SaveAsync 写入一个 IOutputStream,并且 LoadAsync 从一个 IInputStream 中读取。 若要使用 System.IO 文件流,请使用 AsOutputStream 和 AsInputStream 将其转换。 该文件需要使用 using System; 以及using System.IO;和using Windows.Storage.Streams;来等待这些 Windows 运行时方法:

// Save ink strokes to a file.
using (FileStream fileStream = File.Create(filePath))
using (IOutputStream output = fileStream.AsOutputStream())
{
    await inkStrokeContainer.SaveAsync(output);
    await output.FlushAsync();
}

// Load ink strokes from a file.
using (FileStream fileStream = File.OpenRead(filePath))
using (IInputStream input = fileStream.AsInputStream())
{
    await inkStrokeContainer.LoadAsync(input);
}

你可以继续使用 InkToolbar.TargetInkCanvas 将工具栏连接到画布,也可以将 TargetInkPresenter 设置为直接连接到某个 InkPresenter。 若要将自己的工具添加到工具栏,请使用 InkToolbarCustomToolButton 和 InkToolbarCustomToggleButton,如 “自定义墨迹工具栏”中所示。 在迁移之前,请查看已知限制,例如标尺和量角器模板存在的已报告问题。

如果应用必须使用稳定版本,则没有可迁移到的内置墨迹输入控件。 使用 Win2D 呈现笔划并自行处理指针输入,或使用第三方墨迹书写库。 若要替换 InkToolbar,请使用包含 AppBarToggleButton 个项目的 CommandBar。

Win2D

Win2D 包名称已更改,但 API 图面相同:

UWP WinUI 3
Win2D.uwp (NuGet) Microsoft.Graphics.Win2D (NuGet)

所有 Microsoft.Graphics.Canvas.* API(CanvasDevice、、CanvasBitmapCanvasRenderTarget)DrawInk的工作方式都相同。 只有 NuGet 包引用需要更新。

印刷

UWP 打印使用 PrintManager.GetForCurrentView()。 WinUI 3 需要窗口句柄互操作:

// UWP
var printManager = PrintManager.GetForCurrentView();
printManager.PrintTaskRequested += OnPrintTaskRequested;
await PrintManager.ShowPrintUIAsync();

// WinUI 3 — must pass window handle
var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow);
var printManager = PrintManagerInterop.GetForWindow(hwnd);
printManager.PrintTaskRequested += OnPrintTaskRequested;
await PrintManagerInterop.ShowPrintUIForWindowAsync(hwnd);

PrintDocument渲染 API(Paginate、GetPreviewPage、AddPages)未发生变化。

Important

如果省略窗口句柄,PrintManagerInterop.GetForWindow 将引发 COMException。 这是与 FileOpenPicker 相同的互操作模式 - 在 UWP 中使用了 GetForCurrentView() 的任何 API,在 WinUI 3 中都需要窗口句柄。

初学者提示

I'm migrating a UWP app to WinUI 3 using the Windows App SDK.

Apply these substitutions:
- Windows.UI.Xaml.* → Microsoft.UI.Xaml.*
- CoreDispatcher / Dispatcher.RunAsync → DispatcherQueue.TryEnqueue
- ApplicationView → AppWindow + AppWindowTitleBar
- CoreWindow → Microsoft.UI.Xaml.Window
- MessageDialog → ContentDialog (set XamlRoot, not InitializeWithWindow)
- FileOpenPicker / FileSavePicker / FolderPicker → add InitializeWithWindow
- Windows.UI.Notifications → Microsoft.Windows.AppNotifications
- SystemNavigationManager.BackRequested → NavigationView back handling
- Pivot → TabView, NavigationView (top mode), or RadioButtons (no direct equivalent)
- InkCanvas, InkToolbar, InkPresenter, InkStrokeContainer, and the other ink input types → Microsoft.UI.Xaml.Controls (experimental Windows App SDK releases only; if the project uses a stable release, flag them instead)
- Ink members that Windows App SDK 2.5.4-experimental doesn't include (new InkStrokeContainer(), assignments to InkPresenter.StrokeContainer, GetRecognitionResults, UpdateRecognitionResults, IsPenHapticFeedbackEnabled, InkToolbarRulerButton.Ruler, IsRulerButtonCheckedChanged, and progress or byte counts from SaveAsync and LoadAsync) → flag them
- PrintManager.GetForCurrentView → PrintManagerInterop.GetForWindow(hwnd)
- Win2D.uwp NuGet → Microsoft.Graphics.Win2D NuGet
- InkStroke, InkDrawingAttributes, InkPoint, InkStrokeBuilder → no change (Windows.UI.Input.Inking; use using aliases to avoid CS0104)

Do not use any Windows.UI.Xaml.* namespaces in new code.
Do not use CoreDispatcher — use DispatcherQueue.
Do not add InkToolbarEraserKind, SelectedEraser, or other eraser APIs from Windows App SDK 2.4.1-experimental. Version 2.5.4-experimental removed them.
x:Bind defaults to Mode=OneTime. Add Mode=OneWay for any binding that should update at runtime.
Flag any APIs without a direct WinUI 3 equivalent rather than guessing.

项目文件更改

替换 UWP 目标框架:

<!-- Before (UWP) -->
<TargetPlatformVersion>10.0.19041.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>

<!-- After (WinUI 3) -->
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<WindowsSdkPackageVersion>10.0.19041.31</WindowsSdkPackageVersion>

添加Windows 应用 SDK包:

dotnet add package Microsoft.WindowsAppSDK