AGENT SKILL

Reactor 命令绑定与快捷键

reactor-commanding

Reactor 命令处理——出现在多个界面(菜单+工具栏)、需要键盘快捷键或需要 `CanExecute` 的动作。`Command`、`StandardCommand`、`UseCommand`、`CommandHost`。当连接共享动作或快捷键时使用。

License 许可
MIT
最近更新
2026-11-15
Stars
★ 896
Forks
67

01 前言 Front Matter

name
reactor-commanding
description
Reactor commanding — actions that appear in multiple surfaces (menu + toolbar), need keyboard shortcuts, or need `CanExecute`. `Command`, `StandardCommand`, `UseCommand`, `CommandHost`. Use when wiring shared actions or shortcuts.

03 SKILL.md 正文

Commanding in Reactor

Use Command when an action shows up in multiple surfaces (toolbar + menu + context menu), needs a keyboard shortcut, or needs CanExecute disabling. Use a bare Action for one-off button clicks with no reuse.

Controlled prop note: command examples may host controlled inputs such as TextBox(text, onChange). Factory call sites stay plain-valued, but direct reads from migrated element records are Optional<T>; see migration/050-optional-t.md.

Command record

var save = new Command
{
    Label = "Save",                                  // required
    Execute = () => Save(),                          // sync
    // OR:
    ExecuteAsync = async () => await SaveAsync(),    // async (wrap with UseCommand)
    CanExecute = hasChanges,                         // default true
    Icon = SymbolIcon("Save"),
    Description = "Save the document",               // tooltip + a11y
    Accelerator = Accelerator(VirtualKey.S, VirtualKeyModifiers.Control),
    AccessKey = "S",                                 // Alt+key
    DebounceMs = 0,                                  // >0 = leading-edge debounce (needs UseCommand)
};
// Computed: IsEnabled = CanExecute && !IsExecuting && !IsDebouncing

Command<T> is identical but Execute/ExecuteAsync receive a typed parameter — bind the parameter at the call site with MenuItem(cmd, item).

StandardCommand factory

Pre-built commands with correct labels, icons, and accelerators:

var cut    = StandardCommand.Cut(() => CutSelection());
var copy   = StandardCommand.Copy(() => CopySelection());
var paste  = StandardCommand.Paste(() => PasteFromClipboard());
var undo   = StandardCommand.Undo(() => Undo());
var redo   = StandardCommand.Redo(() => Redo());
var delete = StandardCommand.Delete(() => DeleteSelected());
var save   = StandardCommand.Save(async () => await SaveAsync()); // async overload
var open   = StandardCommand.Open(() => OpenFile());

// CanExecute parameter:
var cut2 = StandardCommand.Cut(() => CutSelection(), canExecute: hasSelection);

Also available: SelectAll, Close, Share, Play, Pause, Stop, Forward, Backward.

Command-aware DSL overloads

Define once, bind anywhere:

var save = StandardCommand.Save(() => SaveFile());

Button(save)              // label → content, execute → click, isEnabled → isEnabled
AppBarButton(save)        // + icon, accelerator, accessKey, description
MenuItem(save)            // + icon, accelerator, accessKey, description
MenuItem(deleteCmd, item) // parameterized: binds item as argument

Custom content (icon + label, stacked layouts) — build the element, then attach the command with the .Command() modifier. Works on Button, HyperlinkButton, RepeatButton, ToggleButton, and AppBarButton:

// Factory takes a text label only:
Button(save)

// .Command() binds execute + isEnabled + icon/accelerator/accessKey/description
// onto any custom-content clickable, and auto-disables while !command.IsEnabled:
Button(HStack(Icon(SymbolIcon("Save")), TextBlock("Save"))).Command(save)

.Command() re-applies IsEnabled on every update (so UseCommand toggling IsExecuting, or CanExecute changes, flow through) — never re-thread .IsEnabled(command.IsEnabled) by hand. It composes with .IsDisabledFocusable(): a disabled command keeps the button reachable via Tab instead of dropping it from the tab order.

Per-site overrides with with:

var delete = StandardCommand.Delete(() => DeleteSelected());
MenuItem(delete)                                          // "Delete"
MenuItem(delete with { Label = "Remove permanently" })
AppBarButton(delete with { Icon = SymbolIcon("Clear") })

UseCommand — async lifecycle

Only needed for commands with ExecuteAsync. Sync commands pass through unchanged.

class Editor : Component
{
    public override Element Render()
    {
        var saveCmd = UseCommand(StandardCommand.Save(async () =>
        {
            await SaveAsync();
        }));

        // saveCmd.Execute is now a sync wrapper around the async
        // saveCmd.IsExecuting is true while the async is in-flight
        // saveCmd.IsEnabled auto-flips to false while executing
        return HStack(
            Button(saveCmd),
            saveCmd.IsExecuting ? ProgressRing() : Empty());
    }
}
  • Consumes 2 hook slots; re-entrance guard ignores clicks while executing.
  • IsExecuting resets to false even if ExecuteAsync throws.
  • Call unconditionally — don't wrap in if.
  • DebounceMs > 0 adds leading-edge debounce: the first fire runs, re-fires within the window are dropped, and IsEnabled is false for the duration so the button auto-disables then re-enables. Replaces the Task.Delay-to-absorb-double-clicks workaround. Needs UseCommand to persist the window — a raw new Command { DebounceMs = … } bound directly does not debounce. Works on sync Execute too (stays on the UI thread; no Task.Run hop). For async commands the disabled window is the longer of the lambda lifetime and DebounceMs.

CommandHost — keyboard-scoped accelerators

Limits Accelerator registration to a subtree:

var save = StandardCommand.Save(() => SaveFile());
var undo = StandardCommand.Undo(() => UndoAction());

CommandHost([save, undo],
    VStack(
        TextBlock("Ctrl+S / Ctrl+Z only fire inside this region"),
        TextBox(value, onChange)))

Commands without an Accelerator are ignored by CommandHost.

Sharing commands via Context

Editor-provides / toolbar-consumes:

record EditorCommands(Command Save, Command Undo, Command Redo);
static readonly Context<EditorCommands?> EditorCtx = new(null);

class Editor : Component
{
    public override Element Render()
    {
        var save = UseCommand(StandardCommand.Save(async () => await SaveAsync()));
        var undo = StandardCommand.Undo(() => Undo());
        return TextBox(text, onChange)
            .Provide(EditorCtx, new EditorCommands(save, undo, redo));
    }
}

class Toolbar : Component
{
    public override Element Render()
    {
        var cmds = UseContext(EditorCtx);
        if (cmds is null) return Empty();
        return CommandBar(primaryCommands: [
            AppBarButton(cmds.Save),
            AppBarButton(cmds.Undo),
        ]);
    }
}

ICommand interop

Bridge existing MVVM/CommunityToolkit ICommand:

var cmd = CommandInterop.FromCommand(
    viewModel.SaveCommand,
    "Save",
    icon: SymbolIcon("Save"),
    accelerator: Accelerator(VirtualKey.S, VirtualKeyModifiers.Control));

Anti-patterns

  • Don't create commands inside loops. Define once, bind per item with MenuItem(cmd, item).
  • Don't UseCommand for sync-only commands — it wastes hook slots.
  • Don't call UseCommand conditionally — hooks must run in the same order every render.
  • Don't mix Execute and ExecuteAsync on the same command — pick one.

04 同仓库更多 Skills

microsoft
microsoft/microsoft-ui-reactor

图表制作

Charting

暂无简介

数据分析师数据分析与报告
★ 896
microsoft
microsoft/microsoft-ui-reactor

Reactor 控件包装生成

reactor-wrapping

借助 `[GenerateReactorWrapper]` 源生成器,将任意 WinUI 控件——供应商/第三方控件、自定义 `Control` 或 Windows Community Toolkit 控件——转换为一等公民的声明式 Reactor 元素,无需手写任何包装代码。涵盖自动推断(属性、内容、双向绑定对、面板/条目子元素、事件)、`[Wrap*]` 注解速查表、命令式生命周期控件、诊断,以及何时回退到手写 `ControlDescriptor`。

软件开发工程师前端开发与界面实现
★ 896
microsoft
microsoft/microsoft-ui-reactor

Reactor 顶层窗口管理

reactor-windowing

Reactor 顶层窗口开发指南:`WindowSpec`、`OpenWindow`、可拖动窗口、无边框/工具窗口、窗口位置持久化、任务栏可见性、z-order 层级、宽高比、`SizeToContent`、多显示器、任务栏集成,以及基于所有者窗口的文件/文件夹选择器。

软件开发工程师前端开发与界面实现
★ 896
microsoft
microsoft/microsoft-ui-reactor

Reactor 即用型代码配方

reactor-recipes

按意图索引、可直接粘贴使用的单文件 Reactor 配方——支持增删与切换的列表、页面间侧边栏导航、带校验与提交门控的表单、带加载/错误/数据状态的异步获取、Win11 主题卡片界面。使用现成配方而非根据文字描述自行拼凑:复制、调整、即可交付。

软件开发工程师前端开发与界面实现
★ 896
microsoft
microsoft/microsoft-ui-reactor

Reactor 页面导航与路由

reactor-navigation

Reactor 导航——`UseNavigation` 钩子、`NavigationHost` 渲染器、`NavigationView` 侧边栏、`TabView` 标签页、路由参数、栈操作、页面生命周期、深链接、转场动画、缓存。适用于构建多页面应用或接入侧边栏/标签页导航时。

软件开发工程师前端开发与界面实现
★ 896
microsoft
microsoft/microsoft-ui-reactor

Reactor 输入交互处理

reactor-input

Reactor 输入处理——手势(`OnPan`、`OnPinch`、`OnRotate`)、指针事件、拖放(`OnDragStarting`)、焦点管理(`UseElementFocus`、`UseFocus`、`UseFocusTrap`)。在实现直接操作交互或自定义焦点行为时使用。

软件开发工程师前端开发与界面实现
★ 896