csharp-winui
C# 14 and WinUI 3 code rules for Windows apps, including threading, x:Bind, observable models, SQLite, Win32 interop, and fixes for common build and launch errors. Use when writing, reviewing, or debugging C# or XAML in a WinUI app, or on XamlParseException, 0xC000027B crashes, binding, or threading errors.
daveebbelaar · 已有静态检查记录
安装与使用
运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。
npx skills add daveebbelaar/bawa --skill csharp-winui技能说明
name: csharp-winui description: C# 14 and WinUI 3 code rules for Windows apps, including threading, x:Bind, observable models, SQLite, Win32 interop, and fixes for common build and launch errors. Use when writing, reviewing, or debugging C# or XAML in a WinUI app, or on XamlParseException, 0xC000027B crashes, binding, or threading errors.
C# and WinUI
The code is right when it builds with zero warnings, launches without a
CRASH line, and the app does what the story says. For how it should
look, call the Skill tool with windows-design. For copyable XAML, read
../../design/windows-design/patterns.md.
Threads
WinUI has one UI thread per window. Every control and every object bound to a control lives on it.
| Work | Put it in |
|---|---|
Pages, view models, ObservableCollections bound to lists | The UI thread (the default in event handlers and OnLaunched) |
| CPU-heavy pure work (parsing, image work, diffing) | await Task.Run(() => ...), then set results back on the UI thread |
| File and database work | async methods; small SQLite calls on the UI thread are fine, anything over a few ms goes to Task.Run |
| A Win32 callback (hotkey, hook, timer from another thread) | Hop back with DispatcherQueue.TryEnqueue(() => ...) |
awaitin an event handler returns to the UI thread on its own. InsideTask.Runyou are on a pool thread: never touch a control there.async voidonly for event handlers. Everything else returnsTask.- Keep the
DispatcherQueueof the window (window.DispatcherQueue) for code that runs outside a page. - A crash on a background thread kills the app with no
CRASHline fromUnhandledException. Catch and log in everyTask.Runbody you start and forget, and run every background path once after changing it.
State
- Models are
partial class X : ObservableObjectwith[ObservableProperty] public partial string Title { get; set; }(CommunityToolkit.Mvvm 8.4 and C# 14). Initialize partial properties in the constructor: they cannot have initializers. [NotifyPropertyChangedFor(nameof(DisplayTitle))]for computed properties.- Lists bind to an
ObservableCollection<T>. Rebuild it in place (Clear,Add), never assign a new collection to a bound property. x:Bindis compiled and checked, so prefer it over{Binding}. Its default mode is OneTime: writeMode=OneWayfor anything that changes andMode=TwoWayfor inputs, andUpdateSourceTrigger=PropertyChangedon aTextBoxthat saves as you type.- After changing the object a page binds through (
Model.Selection), callBindings.Update()if the binding path starts above the changed object. - JSON goes through source generation: add each saved type to
AppJson([JsonSerializable(typeof(T))]) and passAppJson.Default.T. Reflection JSON breaks under NativeAOT and trimming (IL2026,IL3050). - Small preferences go in
Prefs(JSON next to the database). Unpackaged apps have noApplicationData.Current.LocalSettings: it throws. Secrets go in the Windows Credential Locker (PasswordVault) or DPAPI (ProtectedData), never in the JSON. - A property set to the value it already has fires no change. Fill lists
in the constructor too, not only in
OnXChanged.
SQLite
- One
SqliteConnectionper app, opened once, WAL mode, in<App>.Core. - Schema changes are new steps in
ItemStore.Migrations, keyed byPRAGMA user_version. Never edit a step that shipped. A new column has aDEFAULT, so old files keep loading. - Every row has a
Guidid. Never use the row number or list index as an identity. APP_STOREoverrides the path, and the app refuses test modes unless it points into%TEMP%. Tests never touch%LOCALAPPDATA%\<App>\<App>.db.- Undo: keep the deleted model in memory and save it back. SQLite has no undo of its own across commits.
- Several processes on one file (a CLI, a second instance): send commands
to the running app instead (
agent-cli), so the file keeps one writer.
Commands and keys
- Every command is a button or menu item with a
KeyboardAccelerator. The accelerator works wherever focus is in the window. - Keys that also mean something while typing (Delete, Backspace, arrows,
Enter, plain letters) are scoped:
ScopeOwner="{x:Bind List}", and setargs.Handled = trueinInvoked. - Flyout and context menu items are not in the visual tree: they get no
DataContext. Pass the row withTag="{x:Bind}".
Names that collide
Window, Page, Frame, Layout, Path, Rectangle, Grid, Color,
Colors, Thickness, Point, Size, and Application all exist in WinUI
namespaces. Do not name your own types after them. Path collides with
System.IO.Path as soon as a file imports Microsoft.UI.Xaml.Shapes:
write System.IO.Path. Task collides with System.Threading.Tasks.Task:
name a to-do Todo or TaskItem.
Namespaces collide too, and worse. C# looks for a name in the
enclosing namespaces before the using lines. A namespace
MyApp.Features.Windows makes Windows.Foundation mean
MyApp.Features.Windows.Foundation in every sibling namespace
(CS0234); MyApp.Features.Clipboard hides the WinRT Clipboard class;
Colors and Launcher do the same. Each feature compiles alone, and the
break shows only when two are merged. Never name a namespace segment
Windows, Microsoft, System, or after a type you call
(Clipboard, Colors, Launcher): use Snapping, ClipboardHistory,
Palette, AppLauncher.
Win32 interop
WinUI covers windows, pages, and controls. Win32 is still the answer for:
- The window handle:
WinRT.Interop.WindowNative.GetWindowHandle(window). - Pickers and dialogs from WinRT (
FileOpenPicker,FolderPicker):WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd), or they throw. - DPI:
GetDpiForWindow.AppWindowsizes are physical pixels; XAML