winui3-migration-guide

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

WinUI 3 Migration Guide

WinUI 3 迁移指南

Use this skill when migrating UWP apps to WinUI 3 / Windows App SDK, or when verifying that generated code uses correct WinUI 3 APIs instead of legacy UWP patterns.

当你将 UWP 应用迁移到 WinUI 3 / Windows App SDK,或者验证生成的代码是否使用了正确的 WinUI 3 API 而非旧版 UWP 模式时,可以使用这份参考。

Namespace Changes

命名空间变更

All
Windows.UI.Xaml.*
namespaces move to
Microsoft.UI.Xaml.*
:
UWP NamespaceWinUI 3 Namespace
Windows.UI.Xaml
Microsoft.UI.Xaml
Windows.UI.Xaml.Controls
Microsoft.UI.Xaml.Controls
Windows.UI.Xaml.Media
Microsoft.UI.Xaml.Media
Windows.UI.Xaml.Input
Microsoft.UI.Xaml.Input
Windows.UI.Xaml.Data
Microsoft.UI.Xaml.Data
Windows.UI.Xaml.Navigation
Microsoft.UI.Xaml.Navigation
Windows.UI.Xaml.Shapes
Microsoft.UI.Xaml.Shapes
Windows.UI.Composition
Microsoft.UI.Composition
Windows.UI.Input
Microsoft.UI.Input
Windows.UI.Colors
Microsoft.UI.Colors
Windows.UI.Text
Microsoft.UI.Text
Windows.UI.Core
Microsoft.UI.Dispatching
(for dispatcher)

所有
Windows.UI.Xaml.*
命名空间都迁移到
Microsoft.UI.Xaml.*
UWP NamespaceWinUI 3 Namespace
Windows.UI.Xaml
Microsoft.UI.Xaml
Windows.UI.Xaml.Controls
Microsoft.UI.Xaml.Controls
Windows.UI.Xaml.Media
Microsoft.UI.Xaml.Media
Windows.UI.Xaml.Input
Microsoft.UI.Xaml.Input
Windows.UI.Xaml.Data
Microsoft.UI.Xaml.Data
Windows.UI.Xaml.Navigation
Microsoft.UI.Xaml.Navigation
Windows.UI.Xaml.Shapes
Microsoft.UI.Xaml.Shapes
Windows.UI.Composition
Microsoft.UI.Composition
Windows.UI.Input
Microsoft.UI.Input
Windows.UI.Colors
Microsoft.UI.Colors
Windows.UI.Text
Microsoft.UI.Text
Windows.UI.Core
Microsoft.UI.Dispatching
(for dispatcher)

Top 3 Most Common Copilot Mistakes

Copilot 最常见的 3 个错误

1. ContentDialog Without XamlRoot

1. ContentDialog 未设置 XamlRoot

csharp
// ❌ WRONG — Throws InvalidOperationException in WinUI 3
var dialog = new ContentDialog
{
    Title = "Error",
    Content = "Something went wrong.",
    CloseButtonText = "OK"
};
await dialog.ShowAsync();
csharp
// ✅ CORRECT — Set XamlRoot before showing
var dialog = new ContentDialog
{
    Title = "Error",
    Content = "Something went wrong.",
    CloseButtonText = "OK",
    XamlRoot = this.Content.XamlRoot  // Required in WinUI 3
};
await dialog.ShowAsync();
csharp
// ❌ WRONG — Throws InvalidOperationException in WinUI 3
var dialog = new ContentDialog
{
    Title = "Error",
    Content = "Something went wrong.",
    CloseButtonText = "OK"
};
await dialog.ShowAsync();
csharp
// ✅ CORRECT — Set XamlRoot before showing
var dialog = new ContentDialog
{
    Title = "Error",
    Content = "Something went wrong.",
    CloseButtonText = "OK",
    XamlRoot = this.Content.XamlRoot  // Required in WinUI 3
};
await dialog.ShowAsync();

2. MessageDialog Instead of ContentDialog

2. 使用 MessageDialog 而非 ContentDialog

csharp
// ❌ WRONG — UWP API, not available in WinUI 3 desktop
var dialog = new Windows.UI.Popups.MessageDialog("Are you sure?", "Confirm");
await dialog.ShowAsync();
csharp
// ✅ CORRECT — Use ContentDialog
var dialog = new ContentDialog
{
    Title = "Confirm",
    Content = "Are you sure?",
    PrimaryButtonText = "Yes",
    CloseButtonText = "No",
    XamlRoot = this.Content.XamlRoot
};
var result = await dialog.ShowAsync();
if (result == ContentDialogResult.Primary)
{
    // User confirmed
}
csharp
// ❌ WRONG — UWP API, not available in WinUI 3 desktop
var dialog = new Windows.UI.Popups.MessageDialog("Are you sure?", "Confirm");
await dialog.ShowAsync();
csharp
// ✅ CORRECT — Use ContentDialog
var dialog = new ContentDialog
{
    Title = "Confirm",
    Content = "Are you sure?",
    PrimaryButtonText = "Yes",
    CloseButtonText = "No",
    XamlRoot = this.Content.XamlRoot
};
var result = await dialog.ShowAsync();
if (result == ContentDialogResult.Primary)
{
    // User confirmed
}

3. CoreDispatcher Instead of DispatcherQueue

3. 使用 CoreDispatcher 而非 DispatcherQueue

csharp
// ❌ WRONG — CoreDispatcher does not exist in WinUI 3
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
    StatusText.Text = "Done";
});
csharp
// ✅ CORRECT — Use DispatcherQueue
DispatcherQueue.TryEnqueue(() =>
{
    StatusText.Text = "Done";
});

// With priority:
DispatcherQueue.TryEnqueue(DispatcherQueuePriority.High, () =>
{
    ProgressBar.Value = 100;
});

csharp
// ❌ WRONG — CoreDispatcher does not exist in WinUI 3
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
    StatusText.Text = "Done";
});
csharp
// ✅ CORRECT — Use DispatcherQueue
DispatcherQueue.TryEnqueue(() =>
{
    StatusText.Text = "Done";
});

// With priority:
DispatcherQueue.TryEnqueue(DispatcherQueuePriority.High, () =>
{
    ProgressBar.Value = 100;
});

Windowing Migration

窗口管理迁移

Window Reference

窗口引用

csharp
// ❌ WRONG — Window.Current does not exist in WinUI 3
var currentWindow = Window.Current;
csharp
// ✅ CORRECT — Use a static property in App
public partial class App : Application
{
    public static Window MainWindow { get; private set; }

    protected override void OnLaunched(LaunchActivatedEventArgs args)
    {
        MainWindow = new MainWindow();
        MainWindow.Activate();
    }
}
// Access anywhere: App.MainWindow
csharp
// ❌ WRONG — Window.Current does not exist in WinUI 3
var currentWindow = Window.Current;
csharp
// ✅ CORRECT — Use a static property in App
public partial class App : Application
{
    public static Window MainWindow { get; private set; }

    protected override void OnLaunched(LaunchActivatedEventArgs args)
    {
        MainWindow = new MainWindow();
        MainWindow.Activate();
    }
}
// Access anywhere: App.MainWindow

Window Management

窗口管理API对应

UWP APIWinUI 3 API
ApplicationView.TryResizeView()
AppWindow.Resize()
AppWindow.TryCreateAsync()
AppWindow.Create()
AppWindow.TryShowAsync()
AppWindow.Show()
AppWindow.TryConsolidateAsync()
AppWindow.Destroy()
AppWindow.RequestMoveXxx()
AppWindow.Move()
AppWindow.GetPlacement()
AppWindow.Position
property
AppWindow.RequestPresentation()
AppWindow.SetPresenter()
UWP APIWinUI 3 API
ApplicationView.TryResizeView()
AppWindow.Resize()
AppWindow.TryCreateAsync()
AppWindow.Create()
AppWindow.TryShowAsync()
AppWindow.Show()
AppWindow.TryConsolidateAsync()
AppWindow.Destroy()
AppWindow.RequestMoveXxx()
AppWindow.Move()
AppWindow.GetPlacement()
AppWindow.Position
property
AppWindow.RequestPresentation()
AppWindow.SetPresenter()

Title Bar

标题栏

UWP APIWinUI 3 API
CoreApplicationViewTitleBar
AppWindowTitleBar
CoreApplicationView.TitleBar.ExtendViewIntoTitleBar
AppWindow.TitleBar.ExtendsContentIntoTitleBar

UWP APIWinUI 3 API
CoreApplicationViewTitleBar
AppWindowTitleBar
CoreApplicationView.TitleBar.ExtendViewIntoTitleBar
AppWindow.TitleBar.ExtendsContentIntoTitleBar

Dialogs and Pickers Migration

对话框与选择器迁移

File/Folder Pickers

文件/文件夹选择器

csharp
// ❌ WRONG — UWP style, no window handle
var picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".txt");
var file = await picker.PickSingleFileAsync();
csharp
// ✅ CORRECT — Initialize with window handle
var picker = new FileOpenPicker();
var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow);
WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd);
picker.FileTypeFilter.Add(".txt");
var file = await picker.PickSingleFileAsync();
csharp
// ❌ WRONG — UWP style, no window handle
var picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".txt");
var file = await picker.PickSingleFileAsync();
csharp
// ✅ CORRECT — Initialize with window handle
var picker = new FileOpenPicker();
var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow);
WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd);
picker.FileTypeFilter.Add(".txt");
var file = await picker.PickSingleFileAsync();

Threading Migration

线程处理迁移

UWP PatternWinUI 3 Equivalent
CoreDispatcher.RunAsync(priority, callback)
DispatcherQueue.TryEnqueue(priority, callback)
Dispatcher.HasThreadAccess
DispatcherQueue.HasThreadAccess
CoreDispatcher.ProcessEvents()
No equivalent — restructure async code
CoreWindow.GetForCurrentThread()
Not available — use
DispatcherQueue.GetForCurrentThread()
Key difference: UWP uses ASTA (Application STA) with built-in reentrancy blocking. WinUI 3 uses standard STA without this protection. Watch for reentrancy issues when async code pumps messages.

UWP PatternWinUI 3 Equivalent
CoreDispatcher.RunAsync(priority, callback)
DispatcherQueue.TryEnqueue(priority, callback)
Dispatcher.HasThreadAccess
DispatcherQueue.HasThreadAccess
CoreDispatcher.ProcessEvents()
No equivalent — restructure async code
CoreWindow.GetForCurrentThread()
Not available — use
DispatcherQueue.GetForCurrentThread()
关键差异:UWP 使用带有内置重入阻塞的 ASTA(Application STA)模型,WinUI 3 使用无该保护的标准 STA 模型。当异步代码泵送消息时,请注意重入问题。

Background Tasks Migration

后台任务迁移

csharp
// ❌ WRONG — UWP IBackgroundTask
public sealed class MyTask : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance) { }
}
csharp
// ✅ CORRECT — Windows App SDK AppLifecycle
using Microsoft.Windows.AppLifecycle;

// Register for activation
var args = AppInstance.GetCurrent().GetActivatedEventArgs();
if (args.Kind == ExtendedActivationKind.AppNotification)
{
    // Handle background activation
}

csharp
// ❌ WRONG — UWP IBackgroundTask
public sealed class MyTask : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance) { }
}
csharp
// ✅ CORRECT — Windows App SDK AppLifecycle
using Microsoft.Windows.AppLifecycle;

// Register for activation
var args = AppInstance.GetCurrent().GetActivatedEventArgs();
if (args.Kind == ExtendedActivationKind.AppNotification)
{
    // Handle background activation
}

App Settings Migration

应用设置迁移

ScenarioPackaged AppUnpackaged App
Simple settings
ApplicationData.Current.LocalSettings
JSON file in
LocalApplicationData
Local file storage
ApplicationData.Current.LocalFolder
Environment.GetFolderPath(SpecialFolder.LocalApplicationData)

场景打包应用未打包应用
简单设置
ApplicationData.Current.LocalSettings
JSON file in
LocalApplicationData
本地文件存储
ApplicationData.Current.LocalFolder
Environment.GetFolderPath(SpecialFolder.LocalApplicationData)

GetForCurrentView() Replacements

GetForCurrentView() 替换方案

All
GetForCurrentView()
patterns are unavailable in WinUI 3 desktop apps:
UWP APIWinUI 3 Replacement
UIViewSettings.GetForCurrentView()
Use
AppWindow
properties
ApplicationView.GetForCurrentView()
AppWindow.GetFromWindowId(windowId)
DisplayInformation.GetForCurrentView()
Win32
GetDpiForWindow()
or
XamlRoot.RasterizationScale
CoreApplication.GetCurrentView()
Not available — track windows manually
SystemNavigationManager.GetForCurrentView()
Handle back navigation in
NavigationView
directly

WinUI 3 桌面应用中不支持所有
GetForCurrentView()
模式:
UWP APIWinUI 3 Replacement
UIViewSettings.GetForCurrentView()
Use
AppWindow
properties
ApplicationView.GetForCurrentView()
AppWindow.GetFromWindowId(windowId)
DisplayInformation.GetForCurrentView()
Win32
GetDpiForWindow()
or
XamlRoot.RasterizationScale
CoreApplication.GetCurrentView()
Not available — track windows manually
SystemNavigationManager.GetForCurrentView()
Handle back navigation in
NavigationView
directly

Testing Migration

测试迁移

UWP unit test projects do not work with WinUI 3. You must migrate to the WinUI 3 test project templates.
UWPWinUI 3
Unit Test App (Universal Windows)Unit Test App (WinUI in Desktop)
Standard MSTest project with UWP typesMust use WinUI test app for Xaml runtime
[TestMethod]
for all tests
[TestMethod]
for logic,
[UITestMethod]
for XAML/UI tests
Class Library (Universal Windows)Class Library (WinUI in Desktop)
csharp
// ✅ WinUI 3 unit test — use [UITestMethod] for any XAML interaction
[UITestMethod]
public void TestMyControl()
{
    var control = new MyLibrary.MyUserControl();
    Assert.AreEqual(expected, control.MyProperty);
}
Key: The
[UITestMethod]
attribute tells the test runner to execute the test on the XAML UI thread, which is required for instantiating any
Microsoft.UI.Xaml
type.

UWP 单元测试项目无法在 WinUI 3 中运行,你必须迁移到 WinUI 3 测试项目模板。
UWPWinUI 3
Unit Test App (Universal Windows)Unit Test App (WinUI in Desktop)
Standard MSTest project with UWP typesMust use WinUI test app for Xaml runtime
[TestMethod]
for all tests
[TestMethod]
for logic,
[UITestMethod]
for XAML/UI tests
Class Library (Universal Windows)Class Library (WinUI in Desktop)
csharp
// ✅ WinUI 3 unit test — use [UITestMethod] for any XAML interaction
[UITestMethod]
public void TestMyControl()
{
    var control = new MyLibrary.MyUserControl();
    Assert.AreEqual(expected, control.MyProperty);
}
要点
[UITestMethod]
属性会告诉测试运行器在 XAML UI 线程上执行测试,实例化任何
Microsoft.UI.Xaml
类型都需要该配置。

Migration Checklist

迁移检查清单

  1. Replace all
    Windows.UI.Xaml.*
    using directives with
    Microsoft.UI.Xaml.*
  2. Replace
    Windows.UI.Colors
    with
    Microsoft.UI.Colors
  3. Replace
    CoreDispatcher.RunAsync
    with
    DispatcherQueue.TryEnqueue
  4. Replace
    Window.Current
    with
    App.MainWindow
    static property
  5. Add
    XamlRoot
    to all
    ContentDialog
    instances
  6. Initialize all pickers with
    InitializeWithWindow.Initialize(picker, hwnd)
  7. Replace
    MessageDialog
    with
    ContentDialog
  8. Replace
    ApplicationView
    /
    CoreWindow
    with
    AppWindow
  9. Replace
    CoreApplicationViewTitleBar
    with
    AppWindowTitleBar
  10. Replace all
    GetForCurrentView()
    calls with
    AppWindow
    equivalents
  11. Update interop for Share and Print managers
  12. Replace
    IBackgroundTask
    with
    AppLifecycle
    activation
  13. Update project file: TFM to
    net10.0-windows10.0.22621.0
    , add
    <UseWinUI>true</UseWinUI>
  14. Migrate unit tests to Unit Test App (WinUI in Desktop) project; use
    [UITestMethod]
    for XAML tests
  15. Test both packaged and unpackaged configurations
  1. 将所有
    Windows.UI.Xaml.*
    using 指令替换为
    Microsoft.UI.Xaml.*
  2. Windows.UI.Colors
    替换为
    Microsoft.UI.Colors
  3. CoreDispatcher.RunAsync
    替换为
    DispatcherQueue.TryEnqueue
  4. Window.Current
    替换为
    App.MainWindow
    静态属性
  5. 为所有
    ContentDialog
    实例添加
    XamlRoot
    配置
  6. 使用
    InitializeWithWindow.Initialize(picker, hwnd)
    初始化所有选择器
  7. MessageDialog
    替换为
    ContentDialog
  8. ApplicationView
    /
    CoreWindow
    替换为
    AppWindow
  9. CoreApplicationViewTitleBar
    替换为
    AppWindowTitleBar
  10. 将所有
    GetForCurrentView()
    调用替换为对应的
    AppWindow
    实现
  11. 更新分享和打印管理器的互操作逻辑
  12. IBackgroundTask
    替换为
    AppLifecycle
    激活逻辑
  13. 更新项目文件:将 TFM 设置为
    net10.0-windows10.0.22621.0
    ,添加
    <UseWinUI>true</UseWinUI>
    配置
  14. 将单元测试迁移到 Unit Test App (WinUI in Desktop) 项目;针对 XAML 测试使用
    [UITestMethod]
  15. 同时测试打包和未打包两种配置