GuideOpen
WinUI 3 / Windows App SDK
WinUI 3 and Windows App SDK coding guidelines. Prevents common UWP API misuse, enforces correct XAML namespaces, threading, windowing, and MVVM patterns for desktop Windows apps.
Front matter
description: 'WinUI 3 and Windows App SDK coding guidelines. Prevents common UWP API misuse, enforces correct XAML namespaces, threading, windowing, and MVVM patterns for desktop Windows apps.'
applyTo: '**/*.xaml, **/*.cs, **/*.csproj'WinUI 3 / Windows App SDK
Critical Rules — NEVER Use Legacy UWP APIs
These UWP patterns are wrong for WinUI 3 desktop apps. Always use the Windows App SDK equivalent.
- NEVER use
Windows.UI.Popups.MessageDialog. UseContentDialogwithXamlRootset. - NEVER show a
ContentDialogwithout settingdialog.XamlRoot = this.Content.XamlRootfirst. - NEVER use
CoreDispatcher.RunAsyncorDispatcher.RunAsync. UseDispatcherQueue.TryEnqueue. - NEVER use
Window.Current. Track the main window via a staticApp.MainWindowproperty. - NEVER use
Windows.UI.Xaml.namespaces. UseMicrosoft.UI.Xaml.. - NEVER use
Windows.UI.Composition. UseMicrosoft.UI.Composition. - NEVER use
Windows.UI.Colors. UseMicrosoft.UI.Colors. - NEVER use
ApplicationVieworCoreWindowfor window management. UseMicrosoft.UI.Windowing.AppWindow. - NEVER use
CoreApplicationViewTitleBar. UseAppWindowTitleBar. - NEVER use
GetForCurrentView()patterns (e.g.,UIViewSettings.GetForCurrentView()). These do not exist in desktop WinUI 3. UseAppWindowAPIs instead. - NEVER use UWP
PrintManagerdirectly. UseIPrintManagerInteropwith a window handle. - NEVER use
DataTransferManagerdirectly for sharing. UseIDataTransferManagerInteropwith a window handle. - NEVER use UWP
IBackgroundTask. UseMicrosoft.Windows.AppLifecycleactivation. - NEVER use
WebAuthenticationBroker. UseOAuth2Manager(Windows App SDK 1.7+).
XAML Patterns
- The default XAML namespace maps to
Microsoft.UI.Xaml, notWindows.UI.Xaml. - Prefer
{x:Bind}over{Binding}for compiled, type-safe, higher-performance bindings. - Set
x:DataTypeonDataTemplateelements when using{x:Bind}— this is required for compiled bindings in templates. On Page/UserControl,x:DataTypeenables compile-time binding validation but is not strictly required if the DataContext does not change. - Use
Mode=OneWayfor dynamic values,Mode=OneTimefor static,Mode=TwoWayonly for editable inputs. - Do not bind static constants — set them directly in XAML.
Threading
- Use
DispatcherQueue.TryEnqueue(() => { ... })to update UI from background threads. TryEnqueuereturnsbool, not aTask— it is fire-and-forget.- Check thread access with
DispatcherQueue.HasThreadAccessbefore dispatching. - WinUI 3 uses standard STA (not ASTA). No built-in reentrancy protection — be cautious with async code that pumps messages.
Windowing
- Get the
AppWindowfrom a WinUI 3WindowviaWindowNative.GetWindowHandle→Win32Interop.GetWindowIdFromWindow→AppWindow.GetFromWindowId. - Use
AppWindowfor resize, move, title, and presenter operations. - Custom title bar: use
AppWindow.TitleBarproperties, notCoreApplicationViewTitleBar. - Track the main window as
App.MainWindow(a static property set inOnLaunched).
Dialogs and Pickers
- ContentDialog: Always set
dialog.XamlRoot = this.Content.XamlRootbefore callingShowAsync(). - File/Folder Pickers: Initialize with
WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd)wherehwndcomes fromWindowNative.GetWindowHandle(App.MainWindow). - Share/Print: Use COM interop interfaces (
IDataTransferManagerInterop,IPrintManagerInterop) with window handles.
MVVM and Data Binding
- Prefer
CommunityToolkit.Mvvm([ObservableProperty],[RelayCommand]) for MVVM infrastructure. - Use
Microsoft.Extensions.DependencyInjectionfor service registration and injection. - Keep UI (Views) focused on layout and bindings; keep logic in ViewModels and services.
- Use
async/awaitfor I/O and long-running work to keep the UI responsive.
Project Setup
- Target
net10.0-windows10.0.22621.0(or appropriate TFM for the project's target SDK). - Set
<UseWinUI>true</UseWinUI>in the project file. - Reference the latest stable
Microsoft.WindowsAppSDKNuGet package. - Use
System.Text.Jsonwith source generators for JSON serialization.
C# Code Style
- Use file-scoped namespaces.
- Enable nullable reference types. Use
is null/is not nullinstead of== null. - Prefer pattern matching over
as/iswith null checks. - PascalCase for types, methods, properties. camelCase for private fields.
- Allman brace style (opening brace on its own line).
- Prefer explicit types for built-in types; use
varonly when the type is obvious.
Accessibility
- Set
AutomationProperties.Nameon all interactive controls. - Use
AutomationProperties.HeadingLevelon section headers. - Hide decorative elements with
AutomationProperties.AccessibilityView="Raw". - Ensure full keyboard navigation (Tab, Enter, Space, arrow keys).
- Meet WCAG color contrast requirements.
Performance
- Prefer
{x:Bind}(compiled) over{Binding}(reflection-based). - NativeAOT: Under Native AOT compilation,
{Binding}(reflection-based) does not work at all. Only{x:Bind}(compiled bindings) is supported. If the project uses NativeAOT, use{x:Bind}exclusively. - Use
x:Loadorx:DeferLoadStrategyfor UI elements that are not immediately needed. - Use
ItemsRepeaterwith virtualization for large lists. - Avoid deep layout nesting — prefer
Gridover nestedStackPanelchains. - Use
async/awaitfor all I/O; never block the UI thread.
App Settings (Packaged vs Unpackaged)
- Packaged apps:
ApplicationData.Current.LocalSettingsworks as expected. - Unpackaged apps: Use a custom settings file (e.g., JSON in
Environment.GetFolderPath(SpecialFolder.LocalApplicationData)). - Do not assume
ApplicationDatais always available — check packaging status first.
Typography
- Always use built-in TextBlock styles (
CaptionTextBlockStyle,BodyTextBlockStyle,BodyStrongTextBlockStyle,SubtitleTextBlockStyle,TitleTextBlockStyle,TitleLargeTextBlockStyle,DisplayTextBlockStyle). - Prefer using the built-in TextBlock styles over hardcoding
FontSize,FontWeight, orFontFamily. - Font: Segoe UI Variable is the default — do not change it.
- Use sentence casing for all UI text.
Theming & Colors
- Always use
{ThemeResource}for brushes and colors to support Light, Dark, and High Contrast themes automatically. - Never hardcode color values (
#FFFFFF,Colors.White, etc.) for UI elements. Use theme resources likeTextFillColorPrimaryBrush,CardBackgroundFillColorDefaultBrush,CardStrokeColorDefaultBrush. - Use
SystemAccentColor(andLight1–Light3,Dark1–Dark3variants) for the user's accent color palette. - For borders: use
CardStrokeColorDefaultBrushorControlStrokeColorDefaultBrush.
Spacing & Layout
- Use a 4px grid system: all margins, padding, and spacing values must be multiples of 4px.
- Standard spacing: 4 (compact), 8 (controls), 12 (small gutters), 16 (content padding), 24 (large gutters).
- Prefer
Gridover deeply nestedStackPanelchains for performance. - Use
Autofor content-sized rows/columns,*for proportional sizing. Avoid fixed pixel sizes. - Use
VisualStateManagerwithAdaptiveTriggerfor responsive layouts at breakpoints (640px, 1008px). - Use
ControlCornerRadius(4px) for small controls andOverlayCornerRadius(8px) for cards, dialogs, flyouts.
Materials & Elevation
- Use Mica (
MicaBackdrop) for the app window backdrop. Requires transparent layers above to show through. - Use Acrylic for transient surfaces only (flyouts, menus, navigation panes).
- Use
LayerFillColorDefaultBrushfor content layers above Mica. - Use
ThemeShadowwith Z-axisTranslationfor elevation. Cards: 4–8 px, Flyouts: 32 px, Dialogs: 128 px.
Motion & Transitions
- Use built-in theme transitions (
EntranceThemeTransition,RepositionThemeTransition,ContentThemeTransition,AddDeleteThemeTransition). - Avoid custom storyboard animations when a built-in transition exists.
Control Selection
- Use
NavigationViewfor primary app navigation (not custom sidebars). - Use
InfoBarfor persistent in-app notifications (not custom banners). - Use
TeachingTipfor contextual guidance (not custom popups). - Use
NumberBoxfor numeric input (not TextBox with manual validation). - Use
ToggleSwitchfor on/off settings (not CheckBox). - Use
ItemsViewas the modern collection control for displaying data with built-in selection, virtualization, and layout flexibility. - Use
ListView/GridViewfor standard virtualized lists and grids, especially when built-in selection support is needed. - Use
ItemsRepeateronly for fully custom virtualizing layouts where you need complete control over rendering and do not need built-in selection or interaction handling. - Use
Expanderfor collapsible sections (not custom visibility toggling).
Error Handling
- Always wrap
async voidevent handlers in try/catch to prevent unhandled crashes. - Use
InfoBar(withSeverity = Error) for user-facing error messages, notContentDialogfor routine errors. - Handle
App.UnhandledExceptionfor logging and graceful recovery.
Testing
- NEVER use a plain MSTest or xUnit project for tests that instantiate WinUI 3 XAML types. Use a Unit Test App (WinUI in Desktop) project, which provides the Xaml runtime and UI thread.
- Use
[TestMethod]for pure logic tests. Use[UITestMethod]for any test that creates or interacts withMicrosoft.UI.Xamltypes (controls, pages, user controls). - Place testable business logic in a Class Library (WinUI in Desktop) project, separate from the main app.
- Build the solution before running tests to enable Visual Studio test discovery.
Resources & Localization
- Store user-facing strings in
Resources.reswfiles, not in code or XAML literals. - Use
x:Uidin XAML for localized text binding. - Use DPI-qualified image assets (
logo.scale-200.png); reference without scale qualifier (ms-appx:///Assets/logo.png).
Source: https://github.com/github/awesome-copilot/blob/main/instructions/winui3.instructions.md
Author: github, GitHub awesome-copilot. License: MIT.
Shown here with formatting for the web. Keep the author and license notice when you reuse it.
Related entries
There are more like this in the members library
The GitHub Copilot library holds 3,059 entries. Members can search all of them by meaning and read every one in full.