WPF development toolkit with 57 skills, 9 agents, and 5 commands for CustomControl, MVVM, XAML styling, and high-performance rendering

version
1.3.12
GitHub stars
41

Install

/plugin install wpf-dev-pack@dotnet-claude-plugins

Run it inside Claude Code after adding the marketplace with /plugin marketplace add christian289/dotnet-with-claudecode.

Contents

Discovered from source

Skills 28

Collecting wpf-dev-pack Feedback

This skill turns lessons learned in the current WPF session into a structured improvement-feedback document for the wpf-dev-pack plugin. It does NOT modify wpf-dev-pack and does NOT touch git — it only writes one markdown file to the current working directory, which the user later contributes via pull request.

Why this exists

WPF work happens in projects OUTSIDE the dotnet-with-claudecode repository, and that repo's local clone path differs per machine. Editing wpf-dev-pack from a foreign session is infeasible, so improvements are captured as an accumulable md and contributed separately (see the repo CONTRIBUTING guide).

Anonymity policy (MANDATORY)

The feedback document is a reusable artifact contributed across projects. It must describe the technical phenomenon and its causal chain only. The following content is PROHIBITED in any feedback document produced by this skill:

  • Project, solution, repository, product, or codename
  • Team, developer, or user name; email; account handle
  • Date or time of when the issue was encountered
  • Absolute or repo-relative file paths from the originating codebase
  • Class, namespace, or member names that are unique to the originating project (use generic placeholders such as XxxView, XxxViewModel, XxxService)
  • Any other detail that can identify the originating project or person

Public framework / library / API names (e.g., HelixToolkit, ScottPlot, CommunityToolkit.Mvvm, Prism, DispatcherPriority.ApplicationIdle) are allowed because they are part of the technical context, not identifying information.

Workflow

Copy this checklist and track progress:

Feedback Collection Progress:
- [ ] Step 1: Auto-draft feedback items from this session
- [ ] Step 2: Augment via interview (AskUserQuestion)
- [ ] Step 3: Sanitize and rewrite each item as a causal description
- [ ] Step 4: Write the md to the current directory
- [ ] Step 5: Audit the completed md for identifying information
- [ ] Step 6: Report path and contribution instructions

Step 1 — Auto-draft

Review THIS conversation/session and extract feedback candidates. Look for:

  • wpf-dev-pack skills that were used, and where their guidance was inaccurate or insufficient
  • Anti-patterns the user/you hand-fixed that are not yet encoded in any skill
  • Skill or rule content that is missing or outdated
  • Keywords that should have triggered a skill (or triggered the wrong one)
  • make-wpf-* scaffolder output that was missing or wrong

For each candidate, capture concrete session evidence (what was attempted, what broke, how it was fixed) and a concrete proposal (which file to add/change, what kind: new skill / augment skill / scaffolder modernization / rule addition) and a priority (High / Medium / Low).

If no candidate is found, tell the user there is nothing to report and STOP without writing a file.

Step 2 — Interview augmentation

Use the AskUserQuestion tool at least once (one or two questions max) to surface items the auto-draft missed. Suggested questions:

  • "Which skill triggered but gave wrong/incomplete guidance?"
  • "Which pattern did you hand-write that should be scaffolded or documented?"

Fold the answers into the draft.

Step 3 — Sanitize and rewrite as a causal description

Before writing the document, for every drafted item, rewrite the evidence so that it reads as a generic technical phenomenon, not a project incident.

Apply these transformations:

If the draft containsReplace with
A project / solution / repo nameOmit entirely; refer to "a WPF project" or remove the sentence
A developer / team nameOmit entirely
A date / time / sprint referenceOmit entirely
An absolute or repo-relative path from the originating codebaseA generic shape such as Views/XxxView.xaml, ViewModels/XxxViewModel.cs
A project-specific class / namespace / member nameA neutral placeholder such as XxxView, XxxViewModel, IXxxService
"We tried X in project Y""When X is done with this API"
"It broke in our build""The control/binding/render path fails because …"

Each item's evidence section must then describe:

  1. Phenomenon — what is observed (the symptom)
  2. Cause — the framework / library / API behavior that produces it
  3. Effect — the resulting failure mode or wrong output

Keep the chain technical and reproducible by any reader, regardless of which project they are working on.

Step 4 — Write the document

Resolve a short kebab-case <topic> from the $0 argument if provided, else infer it from the session's main subject.

Write the file to <cwd>/<topic>-wpf-dev-pack-feedback.md (current working directory root — do NOT search for or write into any other repo, and do NOT run git). If a file with the same name already exists, append a short disambiguating suffix (e.g., -2) rather than overwriting.

Do NOT prefix the filename with a date (no YYYY-MM-DD-…). The Anonymity policy in this skill forbids dates inside the document body, and the same rule applies to the filename — date prefixes leak when the issue was encountered and defeat anonymity. The filename is exactly <topic>-wpf-dev-pack-feedback.md, nothing prepended.

The document body language is not constrained — use whichever language the session naturally produced (Korean, English, or mixed is all fine). Use this exact structure:

# wpf-dev-pack Feedback — <one-line title>

- **Purpose**: <why this feedback is needed>
- **Scope**: <count of new skills / augmentations / scaffolder modernizations; version bump and README sync notes>

---

## 0. Summary (priority)

| ID | Kind | Target | Priority | One-liner |
|----|------|--------|----------|-----------|
| 1  | New skill / Augment / Modernize / Rule / Knowledge | skills/<...>/SKILL.md or knowledge/<id>/TOPIC.md | High/Medium/Low | ... |

---

## 1. <item title>

### Phenomenon and causality
<Phenomenon: what is observed.
Cause: which framework / library / API behavior produces it.
Effect: the resulting failure mode.
No project name, no developer name, no date, no originating file path,
no project-specific identifier.>

### Proposal (concrete change)
<Which file to add or modify, and what to change>

### Adjacent skill boundaries / cross-links
<Boundary with overlapping skills, and cross-link targets>

Add one numbered ## N. section per feedback item.

Step 5 — Audit the completed md

After the file is written, treat it as an untrusted artifact and run an independent audit against the Anonymity policy. The drafting and the audit must be separate passes — do NOT skip this step even when you are confident the draft is clean.

A skill-scoped PostToolUse hook (declared in this skill's frontmatter, implemented at hooks/FeedbackDocAuditor.cs) performs a pattern-based first-pass audit on every Write/Edit of a *-wpf-dev-pack-feedback.md file while this skill is active. The hook is automatically scoped to this skill's lifetime, so it will not fire during unrelated work in other sessions. On violation it exits with code 2, which surfaces the diagnostic back to this conversation. Treat the hook as a safety net, not a substitute: subtle identifiers (project-specific noun phrases, internal product names) cannot be matched by regex and still require the model audit below.

Read the just-written file back from disk (do not audit the in-memory draft), and verify every checklist item below against the file content:

  • No project / solution / repository / product / codename appears
  • No team / developer / user name, email, or account handle appears
  • No date or time of when the issue was encountered appears
  • No absolute or repo-relative path from the originating codebase appears
  • All project-specific class / namespace / member names have been replaced with neutral placeholders (XxxView, XxxViewModel, IXxxService, etc.)
  • Each ## N. item's evidence section reads as Phenomenon → Cause → Effect, not as a project incident report
  • No remaining 작성일 / 출처 / "Date written" / "Source" / "Originating project" / "Encountered in" style metadata field exists
  • The filename itself carries no date prefix — it is exactly <topic>-wpf-dev-pack-feedback.md, never YYYY-MM-DD-<topic>-…

Public framework / library / API names (HelixToolkit, ScottPlot, CommunityToolkit.Mvvm, Prism, DispatcherPriority.ApplicationIdle, etc.) are part of the technical context — they pass the audit.

If any checklist item fails:

  1. Edit the file in place to fix the violation (replace identifying tokens with neutral placeholders, drop sentences that cannot be salvaged without identifying detail, or rewrite the evidence as a generic technical chain).
  2. Re-read the file from disk and re-run the entire checklist.
  3. Repeat until every item passes.

Do not proceed to Step 6 until the checklist is fully clean.

Step 6 — Report

Report the absolute path of the written file, then instruct the user:

이 md를 dotnet-with-claudecode 저장소의 FeedbackDocs/에 넣어 Pull Request로 기여해주세요. 자세한 절차는 저장소의 CONTRIBUTING 문서를 참조하세요.

Do not commit, push, or attempt to locate the dotnet-with-claudecode repo.

Configuring wpf-dev-pack Language

This skill writes (or updates) a per-project preference file that tells the wpf-dev-pack plugin which language to respond in. A SessionStart hook (hooks/LanguagePreferenceLoader.cs) reads the file on every new conversation and emits a directive into the system context, so the preference takes effect automatically.

When to use

  • The default language of a response does not match what the user wants (typical case: an English-speaking contributor in a project where wpf-dev-pack was originally tuned for Korean responses, or vice versa).
  • The user wants to switch language mid-project.

When NOT to use

  • The user only wants a one-off language switch for the next response — just have them phrase the next message in the target language. Do not write a file for a one-shot.
  • The wpf-dev-pack plugin is not installed in the current project — the SessionStart hook will not run without the plugin.

Workflow

Copy this checklist and track progress:

Configure Progress:
- [ ] Step 1: Detect current state of .claude/wpf-dev-pack.local.md
- [ ] Step 2: Resolve target language (argument or AskUserQuestion)
- [ ] Step 3: Write or update .claude/wpf-dev-pack.local.md
- [ ] Step 4: Confirm and explain when the change takes effect

Step 1 — Detect current state

Check whether .claude/wpf-dev-pack.local.md exists in the current project root. If it does, read its YAML frontmatter and find any existing language: value so the user can see what they are replacing.

If the file does not exist, that is fine — Step 3 will create it.

Step 2 — Resolve target language

If $0 is provided, treat it as a BCP-47 language code (the IETF standard built on ISO 639 language codes):

$0 valueMeaning
ko, ko-KRKorean
en, en-US, en-GBEnglish
ja, ja-JPJapanese
zh, zh-CN, zh-TWChinese
(other)Pass through — the hook will display the raw code

The table above is illustrative, not exhaustive. Claude understands any valid BCP-47 / ISO 639-1 code (Claude Code does not maintain a closed allowlist). Authoritative references for code samples:

Accept the value if it is a non-empty short token (letters, digits, hyphen). Reject and ask for clarification otherwise.

If $0 is missing, use AskUserQuestion with up to 4 options (typically Korean / English / Japanese / Chinese) plus an Other escape for free-form input. Surface the currently configured value from Step 1 so the user can see what they are replacing.

Step 3 — Write or update the file

If the file does not exist, create .claude/wpf-dev-pack.local.md with this minimal structure:

---
language: <code>
---

# wpf-dev-pack — Per-Project Local Settings

This file stores personal, per-project preferences for the wpf-dev-pack
plugin. It is read by the LanguagePreferenceLoader SessionStart hook on
every new conversation in this project.

This file is personal and should not be committed. The repo's
.gitignore covers `.claude/*.local.md`.

If the file already exists, only modify the language: field in its YAML frontmatter — preserve all other settings and the body verbatim. If the frontmatter is missing entirely, prepend one with just the language: field; do not touch the existing body.

Step 4 — Confirm

Tell the user:

  1. Which file was written and which language: value it now contains.
  2. The change does not affect the current conversation. The SessionStart hook runs only at the start of a new session, so the user needs to begin a new conversation for the directive to be injected into the system context.
  3. To revert to the default behavior, delete the file or remove its language: field — the hook will then emit nothing and the plugin's default language behavior applies.

Notes

  • The SessionStart hook adds a recommendation to the system context; it does not hard-switch the model. Claude follows the recommendation by default, and the user can still override at any time ("respond in English please" / "한글로 답해줘").
  • This skill is intentionally NOT auto-triggered. Changing the conversation language is a meaningful side effect, so it must be invoked explicitly.
  • The mechanism is wpf-dev-pack scoped. Other plugins or workflows in the same project are unaffected.

WPF and C# Code Formatting

Applies consistent code style to XAML and C# files.


1. Required Tools

.NET 10 SDK

All commands use dotnet dnx for cross-platform compatibility (Windows, Linux, macOS).

# Verify .NET 10 is available
dotnet --version  # Should be 10.0.x or higher

XamlStyler (XAML Formatting)

Run via dotnet dnx (dotnet tool runner). No manual installation required.

dotnet format (C# Formatting)

Included with .NET SDK by default.


2. Configuration Files

Settings.XamlStyler

Copy from template to workspace root if Settings.XamlStyler doesn't exist.

Template location: templates/Settings.XamlStyler

Key settings:

  • AttributesTolerance: 1 - Allow up to 1 attribute on same line
  • KeepFirstAttributeOnSameLine: true - Keep first attribute on element line

.editorconfig

Copy from template to workspace root if .editorconfig doesn't exist.

Template location: templates/.editorconfig

Key settings:

  • Indentation: 4 spaces
  • Line ending: CRLF (Windows)
  • Max line length: 120

3. Formatting Commands

XAML Formatting

# Format all XAML files in workspace
dotnet dnx -y XamlStyler.Console -- -d "{workspace}" -r -c "{workspace}/Settings.XamlStyler"

# Format single file
dotnet dnx -y XamlStyler.Console -- -f "{file.xaml}" -c "{workspace}/Settings.XamlStyler"

dotnet dnx Options:

  • -y: Auto-accept confirmation prompt
  • --: Separator between dnx options and tool arguments

XamlStyler Options:

  • -d: Target directory
  • -f: Target file
  • -r: Recursive processing
  • -c: Configuration file path

C# Formatting

# Format entire solution
dotnet format "{solution.sln}" --no-restore

# Format specific project only
dotnet format "{project.csproj}" --no-restore

# Format single file
dotnet format "{project.csproj}" --include "{file.cs}" --no-restore

Options:

  • --no-restore: Skip NuGet restore (faster)
  • --include: Target specific file

4. Workflow

Full Formatting

Task Progress:
- [ ] Step 1: Check if Settings.XamlStyler exists, create if not
- [ ] Step 2: Check if .editorconfig exists, create if not
- [ ] Step 3: Run dotnet dnx XamlStyler.Console for XAML formatting
- [ ] Step 4: Run dotnet format for C# formatting

Per-file Formatting (Hook Usage)

- When .xaml file modified: Run dotnet dnx XamlStyler.Console
- When .cs file modified: Run dotnet format

5. Notes

  • Check git status: Verify uncommitted changes before formatting
  • Binary exclusion: bin/, obj/ folders automatically excluded
  • Encoding: UTF-8 with BOM maintained (Visual Studio compatible)

6. References

WPF Behavior Generator

If $0 is empty, use the AskUserQuestion tool to ask: "Enter the Behavior name (e.g., SelectAllOnFocus, DragMove)". Do NOT proceed until a valid name is provided. Use the response as the BehaviorName for all subsequent steps.

Generate a $0Behavior class based on Microsoft.Xaml.Behaviors.Wpf.

  • Replace {TargetType} with the appropriate WPF type (e.g., TextBox, UIElement, Window) based on the behavior name and context.
  • Replace {Namespace} with the project's root namespace detected from csproj or existing code.
  • Replace {Project} with the target project path.

Generated Code

namespace {Namespace}.Behaviors;

public sealed class $0Behavior : Behavior<{TargetType}>
{
    #region Dependency Properties

    public static readonly DependencyProperty IsEnabledProperty =
        DependencyProperty.Register(
            nameof(IsEnabled),
            typeof(bool),
            typeof($0Behavior),
            new PropertyMetadata(true));

    public bool IsEnabled
    {
        get => (bool)GetValue(IsEnabledProperty);
        set => SetValue(IsEnabledProperty, value);
    }

    #endregion

    #region Lifecycle

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Loaded += OnLoaded;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.Loaded -= OnLoaded;
    }

    #endregion

    #region Event Handlers

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        if (!IsEnabled)
        {
            return;
        }

        // TODO: Implement behavior logic
    }

    #endregion
}

XAML Usage

<Window xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:behaviors="clr-namespace:{Namespace}.Behaviors">

    <{TargetType}>
        <b:Interaction.Behaviors>
            <behaviors:$0Behavior IsEnabled="{Binding IsBehaviorEnabled}"/>
        </b:Interaction.Behaviors>
    </{TargetType}>

</Window>

Common Behavior Patterns

Focus Management

public sealed class FocusOnLoadBehavior : Behavior<UIElement>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Loaded += (s, e) => AssociatedObject.Focus();
    }
}

Input Handling

public sealed class EnterKeyBehavior : Behavior<TextBox>
{
    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register(nameof(Command), typeof(ICommand),
            typeof(EnterKeyBehavior));

    public ICommand? Command
    {
        get => (ICommand?)GetValue(CommandProperty);
        set => SetValue(CommandProperty, value);
    }

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.KeyDown += OnKeyDown;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.KeyDown -= OnKeyDown;
    }

    private void OnKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            Command?.Execute(AssociatedObject.Text);
        }
    }
}

Required Package

<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.*" />

File Location

{Project}/
└── Behaviors/
    └── $0Behavior.cs

Best Practices

DODON'T
Unsubscribe events in OnDetachingMissing event unsubscription (memory leak)
Expose settings via DependencyPropertyUse hardcoded values
Apply IsEnabled patternAlways execute without condition
Check AssociatedObject for nullUse without null check

Related

  • /wpf-dev-pack:make-wpf-chatclient emits two worked Behavior<T> instances built on this template: an EnterCommandBehavior (Enter=send / Shift+Enter=newline, IME-safe, via PreviewKeyDown with a Command/CommandParameter DP pair) and a StickToBottomBehavior (pin a streaming ScrollViewer to the newest content unless the user scrolled up). See it for a Command-DP behavior and an event-tracking behavior in context.

WPF Chat Bubble Template Generator

If $0 is empty, use the AskUserQuestion tool to ask: "Enter the chat turn ViewModel name (e.g., ChatTurnViewModel, MessageViewModel)". Do NOT proceed until a valid name is provided. Use the response as the turn ViewModel name for all subsequent steps.

Generate the role-differentiated chat bubble DataTemplate (opposite alignment, distinct background, asymmetric gutter, sized to content) and the $0 turn ViewModel that drives it, for an ItemsControl of chat turns.

  • Replace {Namespace} with the project's root namespace.
  • The bubble hosts a MarkdownPresenter (generate it with /wpf-dev-pack:make-wpf-markdown-presenter) so each turn renders selectable markdown.

The governing rule (full rationale in the styling-chat-bubbles-in-wpf knowledge topic — fetch via WpfDevPackMcp get_wpf_topic): declare the base (assistant) values as Style Setters and the per-role override as a DataTrigger Setter — NEVER set a trigger-controlled property (Background, HorizontalAlignment, Margin) as an inline attribute on the Border. In WPF dependency-property value precedence a local value (an inline attribute) outranks a Style trigger Setter, so an inline attribute silently defeats the role DataTrigger and both roles render identically.

Usage

/wpf-dev-pack:make-wpf-chat-bubble-template ChatTurnViewModel

Generated Code

$0.cs (turn ViewModel)

IsUser discriminates the role; Markdown is the content the streaming orchestrator appends to. Lives in the ViewModels project (no System.Windows).

Skip this file if /wpf-dev-pack:make-wpf-chatclient already emitted a turn ViewModel — emitting both produces a duplicate-type collision. The chatclient's version is this class plus an IsWaiting flag.

namespace {Namespace}.ViewModels;

public sealed partial class $0 : ObservableObject
{
    [ObservableProperty] private bool _isUser;
    [ObservableProperty] private bool _isWaiting;          // "waiting…" until the first streamed token
    [ObservableProperty] private string _markdown = string.Empty;

    // The streaming orchestrator appends tokens here; the bound MarkdownPresenter re-renders.
    public void AppendMarkdown(string delta) => Markdown += delta;
}

Chat list XAML (ItemsControl + bubble DataTemplate)

The default uses stock-WPF brushes so it builds with no UI-kit package:

<ItemsControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:vm="clr-namespace:{Namespace}.ViewModels;assembly={Namespace}.ViewModels"
              xmlns:controls="clr-namespace:{Namespace}.Controls"
              ItemsSource="{Binding Turns}">
    <ItemsControl.ItemTemplate>
        <DataTemplate DataType="{x:Type vm:$0}">
            <Border Padding="10" CornerRadius="6">
                <Border.Style>
                    <Style TargetType="Border">
                        <!-- DEFAULT = ASSISTANT (response): left, neutral background, right gutter -->
                        <Setter Property="HorizontalAlignment" Value="Left"/>
                        <Setter Property="Margin" Value="0,4,48,0"/>
                        <Setter Property="Background" Value="#FFF0F0F0"/>
                        <Style.Triggers>
                            <!-- USER (request): right, tinted background, left gutter -->
                            <DataTrigger Binding="{Binding IsUser}" Value="True">
                                <Setter Property="HorizontalAlignment" Value="Right"/>
                                <Setter Property="Margin" Value="48,4,0,0"/>
                                <Setter Property="Background" Value="#FFD6E8FF"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Border.Style>

                <!-- content hugs (MarkdownPresenter reports a hug desired width);
                     the 48px gutter caps max width = parent - 48 -->
                <controls:MarkdownPresenter Markdown="{Binding Markdown}"/>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Key Rules

RuleWhy
Base values = Style Setter; role override = DataTrigger SetterA local (inline) value outranks a Style trigger Setter, so inline attributes defeat the trigger.
HorizontalAlignment = Left/Right, never StretchStretch forces the bubble to full width; hugging needs Left/Right and a child that reports a hug width.
One asymmetric Margin per roleDoubles as the "who sent it" gutter and the max-width cap (parent − gutter); no separate MaxWidth needed.
Properties constant across roles (Padding, CornerRadius)Safe to leave as inline attributes — never under trigger control.

WPF-UI variant — if (and only if) the project references Wpf.Ui, swap the two Background Setters for theme-aware kit brushes and add xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml": {ui:ThemeResource CardBackgroundFillColorDefaultBrush} (assistant) / {ui:ThemeResource SystemAccentColorPrimaryBrush} (user). Declaring xmlns:ui without the package installed is an MC3074 build error, and an invalid theme-resource key throws XamlParseException at render time — use only keys verified to exist in the kit.

File Location

{Project}.ViewModels/
└── $0.cs
{Project}.WpfApp/
└── Views/  (place the ItemsControl XAML in the chat view)

Related

  • Knowledge (fetch via WpfDevPackMcp get_wpf_topic): styling-chat-bubbles-in-wpf, displaying-selectable-rich-text-in-wpf, managing-styles-resourcedictionary, virtualizing-wpf-ui (for long histories of these bubbles).
  • Sibling scaffolders: /wpf-dev-pack:make-wpf-markdown-presenter (the bubble's content control). This template is one of the pieces emitted by the one-button /wpf-dev-pack:make-wpf-chatclient.

WPF Chat Orchestrator Generator

If $0 is empty, use the AskUserQuestion tool to ask: "Enter the orchestrator class name (e.g., ChatOrchestrator)". Do NOT proceed until a valid name is provided. Use the response as the orchestrator name for all subsequent steps.

Generate $0: a streaming chat orchestrator that decomposes IChatClient.GetStreamingResponseAsync into a stream of UI-agnostic ChatEvents, plus the MCP tool acquisition (McpClient.CreateAsync + StdioClientTransport) that feeds ChatOptions.Tools.

  • Replace {Namespace} with the project's root namespace.
  • The IChatClient is produced by /wpf-dev-pack:make-wpf-chatclient-factory (already wrapped with UseFunctionInvocation, so the tool loop runs automatically).

Full rationale in two knowledge topics (fetch via WpfDevPackMcp get_wpf_topic): hosting-extensions-ai-chatclient-in-wpf-mvvm (Dispatcher marshaling, the yield-illegal-in-catch (CS1631) restructuring, cancellation) and consuming-mcp-tools-in-extensions-ai (there is no McpClientFactory; McpClient is abstract — use the static CreateAsync; off-Dispatcher exit dispose).

⚠️ Verify signatures with HandMirror first

Microsoft.Extensions.AI and the MCP SDK evolve quickly. Before emitting, verify with HandMirror (inspect_nuget_package / inspect_nuget_package_type): Microsoft.Extensions.AI (IChatClient, ChatResponseUpdate, ChatOptions, FunctionCallContent, FunctionResultContent) and ModelContextProtocol (McpClient.CreateAsync, StdioClientTransport, McpClientTool).

Required Packages

<PackageReference Include="Microsoft.Extensions.AI" Version="10.*" />
<PackageReference Include="ModelContextProtocol" Version="1.*" />

ModelContextProtocol 1.x ships the client types (McpClient, StdioClientTransport, McpClientTool) in its ModelContextProtocol.Core dependency — the package reference above still works (Core flows transitively) and the ModelContextProtocol.Client namespace is unchanged.

Usings: the snippets assume these in the target project's GlobalUsings.cs: global using System.Runtime.CompilerServices; ([EnumeratorCancellation]), global using Microsoft.Extensions.AI;, global using ModelContextProtocol.Client;, and global using Microsoft.Extensions.Logging; (ILoggerFactory). ChatSettings is the supporting type emitted by /wpf-dev-pack:make-wpf-chatclient-factory.

Placement: standalone default is {Project}/Services below. In a make-wpf-project solution, prefer the *.ViewModels project (namespace {Namespace}.ViewModels) — every type here is WPF-free, and that placement lets ViewModels consume the orchestrator without referencing the app project (the layout used by the one-button /wpf-dev-pack:make-wpf-chatclient).

Generated Code

ChatEvent.cs (UI-agnostic stream events)

namespace {Namespace}.Services;

public abstract record ChatEvent;
public sealed record ChatText(string Text) : ChatEvent;
public sealed record ToolStarted(string Name, IDictionary<string, object?>? Arguments) : ChatEvent;
public sealed record ToolCompleted(string CallId, object? Result) : ChatEvent;
public sealed record ChatFailed(Exception Error) : ChatEvent;

$0.cs (stream decomposition)

C# forbids yield inside a catch (CS1631). So the loop catches a fault into a flag and yields the failure event after the try/catch closes. A OperationCanceledException is a normal stop (yield break), not a failure.

namespace {Namespace}.Services;

public sealed class $0(IChatClient client, IList<AITool> tools, ChatSettings settings)
{
    private readonly IChatClient _client = client;
    private readonly IList<AITool> _tools = tools;
    private readonly ChatSettings _settings = settings;

    public async IAsyncEnumerable<ChatEvent> SendAsync(
        IList<ChatMessage> history, [EnumeratorCancellation] CancellationToken ct)
    {
        var options = new ChatOptions { Tools = _tools, ModelId = _settings.ModelId };
        await using var e = _client.GetStreamingResponseAsync(history, options, ct).GetAsyncEnumerator(ct);

        while (true)
        {
            ChatResponseUpdate? update = null;
            bool faulted = false; Exception? error = null;
            try
            {
                if (!await e.MoveNextAsync()) { break; }
                update = e.Current;
            }
            catch (OperationCanceledException) { yield break; }
            catch (Exception ex) { faulted = true; error = ex; }   // CS1631: cannot yield here

            if (faulted) { yield return new ChatFailed(error!); yield break; }

            if (!string.IsNullOrEmpty(update!.Text)) { yield return new ChatText(update.Text); }
            foreach (AIContent c in update.Contents)
            {
                if (c is FunctionCallContent call)  { yield return new ToolStarted(call.Name, call.Arguments); }
                if (c is FunctionResultContent res) { yield return new ToolCompleted(res.CallId, res.Result); }
            }
        }
    }
}

Emit text via update.Text (robust across stream/SDK shapes) rather than walking TextContent.

McpToolService.cs (tool acquisition + stdio lifecycle)

There is no McpClientFactory. McpClient is abstract — use the static CreateAsync. Connect once and cache (re-connecting per send re-spawns the child process); dispose off the Dispatcher on app exit.

namespace {Namespace}.Services;

public sealed class McpToolService : IAsyncDisposable
{
    private McpClient? _mcp;
    public IList<McpClientTool> Tools { get; private set; } = [];

    // For a framework-dependent dll: Command="dotnet", Arguments=[dllPath].
    // For a self-contained exe: Command=exePath.
    public async Task ConnectAsync(string serverCommand, IList<string> serverArgs,
        ILoggerFactory? loggerFactory, CancellationToken ct)
    {
        var transport = new StdioClientTransport(new StdioClientTransportOptions
        {
            Name = "tools",
            Command = serverCommand,
            Arguments = serverArgs,
        }, loggerFactory);

        // NOTE: there is NO McpClientFactory. McpClient is abstract — use the static CreateAsync.
        _mcp = await McpClient.CreateAsync(transport, clientOptions: null, loggerFactory: null, ct);
        Tools = await _mcp.ListToolsAsync(cancellationToken: ct); // McpClientTool : AIFunction
    }

    public async ValueTask DisposeAsync()
    {
        if (_mcp is not null) { await _mcp.DisposeAsync(); }
    }
}

McpClientTool : AIFunction, so the acquired tools drop straight into the orchestrator's IList<AITool>:

var options = new ChatOptions { Tools = [.. mcpToolService.Tools], ModelId = modelId };

App exit — dispose the stdio client OFF the Dispatcher

Disposing the stdio client ends its child process. From App.OnExit (UI thread) you must not block sync-over-async, which deadlocks the Dispatcher:

// App.OnExit — bounded, OFF the Dispatcher; never .GetAwaiter().GetResult()/.Wait() on the UI thread.
Task.Run(async () => await _mcpService.DisposeAsync()).Wait(TimeSpan.FromSeconds(3));

How the ViewModel consumes it (Dispatcher marshaling + cancellation)

Async stream continuations are not Dispatcher-affine — marshal each event onto the UI Dispatcher before touching bound state, gate Send with a re-entrancy guard, and treat OperationCanceledException as a normal stop:

private CancellationTokenSource? _cts;
public bool IsStreaming { get; private set; }

private async Task SendAsync()
{
    if (IsStreaming || string.IsNullOrWhiteSpace(Input)) { return; } // re-entrancy + empty guard
    IsStreaming = true;
    _cts = new CancellationTokenSource();
    RaiseCommandStates(); // Send disabled, Stop enabled
    try
    {
        await foreach (ChatEvent ev in _orchestrator.SendAsync(_history, _cts.Token))
        {
            Application.Current.Dispatcher.Invoke(() => Apply(ev)); // marshal before touching bound state
        }
    }
    catch (OperationCanceledException) { /* user pressed Stop — normal, not an error */ }
    finally
    {
        IsStreaming = false;
        _cts.Dispose(); _cts = null;
        RaiseCommandStates();
    }
}

private void Stop() => _cts?.Cancel();
// SendCommand.CanExecute => !IsStreaming && !string.IsNullOrWhiteSpace(Input)
// StopCommand.CanExecute => IsStreaming

The full ViewModel (turns collection, IsWaiting, Apply(ev) switch) is emitted by the one-button /wpf-dev-pack:make-wpf-chatclient. If the ViewModel lives in a WPF-free *.ViewModels project, do NOT call Application.Current.Dispatcher there (P-002) — inject the one-method IUiDispatcher abstraction from make-wpf-chatclient instead.

File Location

{Project}/
└── Services/
    ├── ChatEvent.cs
    ├── $0.cs
    └── McpToolService.cs

Related

  • Knowledge (fetch via WpfDevPackMcp get_wpf_topic): hosting-extensions-ai-chatclient-in-wpf-mvvm, consuming-mcp-tools-in-extensions-ai, threading-wpf-dispatcher, preventing-dispatcher-deadlock.
  • Sibling scaffolders: consumes the IChatClient from /wpf-dev-pack:make-wpf-chatclient-factory. Emitted as part of the one-button /wpf-dev-pack:make-wpf-chatclient.

WPF ChatClient Factory Generator

If $0 is empty, use the AskUserQuestion tool to ask: "Enter the factory class name (e.g., ChatClientFactory)". Do NOT proceed until a valid name is provided. Use the response as the factory name for all subsequent steps.

Generate $0 (implementing I$0): a provider-agnostic IChatClient factory that owns one shared SocketsHttpHandler (a single connection pool) reused by every LLM SDK, plus a MockChatClient so the chat UI runs with no provider or API key.

  • Replace {Namespace} with the project's root namespace.
  • Register the factory as a DI singleton — see "Required: singleton lifetime".

Full rationale in the sharing-httpclient-across-llm-sdks knowledge topic (fetch via WpfDevPackMcp get_wpf_topic): the socket-exhaustion anti-pattern, disposeHandler:false, the per-SDK injection cheat sheet, and the version-floor caveat. The mock is covered in hosting-extensions-ai-chatclient-in-wpf-mvvm.

⚠️ Verify SDK signatures with HandMirror first

Each LLM SDK exposes a different HttpClient injection point and these APIs are version-sensitive. Before emitting, verify the exact signatures with HandMirror (inspect_nuget_package / inspect_nuget_package_type) for whichever providers you include: OpenAI, OllamaSharp, Anthropic.SDK, Google.GenAI, System.ClientModel, Microsoft.Extensions.AI. Do not ship a provider arm you have not verified against the pinned package version.

Required Packages

<PackageReference Include="Microsoft.Extensions.AI" Version="10.*" />
<!-- OPTIONAL — add only the provider SDKs the user asked for: -->
<PackageReference Include="OpenAI" Version="2.*" />
<PackageReference Include="OllamaSharp" Version="5.*" />
<PackageReference Include="Anthropic.SDK" Version="5.*" />
<PackageReference Include="Google.GenAI" Version="1.*" />

Emit only the arms you installed. The canonical class below shows ALL provider arms for reference. A provider arm whose SDK package is not installed is a CS0246 build error — when emitting, keep the Provider.Mock arm, keep each arm whose package you added, and replace every other arm with => throw new NotSupportedException($"Install and wire the {s.Provider} SDK first."). The mock-only emission (no provider SDK at all) is the correct default when no provider was requested.

Usings: the snippets assume global using System.Net.Http;, global using Microsoft.Extensions.AI;, and global using System.Runtime.CompilerServices; (for [EnumeratorCancellation] in the mock) in GlobalUsings.cs. Provider-arm namespaces (e.g. the OpenAI client, System.ClientModel, OllamaSharp, Anthropic.SDK, Google.GenAI types) are version-sensitive — resolve the exact namespaces with HandMirror (inspect_nuget_package → list_namespaces) at emit time and add per-file usings for the arms you keep.

Version-floor caveat: a native SDK may pin Microsoft.Extensions.AI.Abstractions to a higher version than other consumers (e.g. an MCP client library). The bump is safe only when those other consumers depend on a [x, ) floor that accepts the higher version — verify the dependency is a floor, not an exact pin, before bumping.

Generated Code

Supporting types

namespace {Namespace}.Services;

public enum Provider { Mock, Ollama, OpenAI, AzureOpenAI, OpenAICompatible, Anthropic, Gemini }

public sealed record ChatSettings
{
    public Provider Provider { get; init; }
    public string ModelId { get; init; } = string.Empty;
    public string? BaseUrl { get; init; }
}

public interface I$0
{
    IChatClient Create(ChatSettings s, string? apiKey);
}

$0.cs

Every provider path reuses the same _shared handler. Connection pooling lives in SocketsHttpHandler (the pool), not in the per-call HttpClient wrapper — so calling Pooled() fresh on each Create() still reuses sockets. Only the injection shape differs per SDK (instance vs Func<HttpClient>).

namespace {Namespace}.Services;

public sealed class $0 : I$0
{
    // One handler == one connection pool shared by every provider for the app's lifetime.
    private readonly SocketsHttpHandler _shared = new()
    {
        PooledConnectionLifetime = TimeSpan.FromMinutes(15)
    };

    // Lightweight wrapper; disposeHandler:false keeps the shared pool alive when the
    // wrapper (or a chat client that owns it) is disposed.
    private HttpClient Pooled() => new(_shared, disposeHandler: false);

    public IChatClient Create(ChatSettings s, string? apiKey)
    {
        IChatClient inner = s.Provider switch
        {
            Provider.Mock              => new MockChatClient(),                 // no HttpClient
            Provider.Ollama            => CreateOllama(s),
            Provider.OpenAI
              or Provider.AzureOpenAI
              or Provider.OpenAICompatible => CreateOpenAiFamily(s, apiKey),
            Provider.Anthropic         => CreateAnthropic(s, apiKey),
            Provider.Gemini            => CreateGemini(s, apiKey),
            _ => throw new InvalidOperationException($"Unsupported provider: {s.Provider}")
        };
        return new ChatClientBuilder(inner)
            .UseFunctionInvocation(loggerFactory: null, configure: null)
            .Build();
    }

    // OpenAI family (incl. Azure & OpenAI-compatible): handler via Transport on the options.
    private IChatClient CreateOpenAiFamily(ChatSettings s, string? apiKey)
    {
        var options = new OpenAIClientOptions
        {
            Transport = new HttpClientPipelineTransport(Pooled()) // System.ClientModel.Primitives
        };
        if (!string.IsNullOrWhiteSpace(s.BaseUrl)) { options.Endpoint = new Uri(s.BaseUrl); }
        return new OpenAIClient(new ApiKeyCredential(apiKey!), options)
            .GetChatClient(s.ModelId)
            .AsIChatClient();
    }

    // OllamaSharp: HttpClient is a direct ctor arg; it implements IChatClient explicitly.
    private IChatClient CreateOllama(ChatSettings s)
    {
        HttpClient http = Pooled();
        http.BaseAddress = new Uri(string.IsNullOrWhiteSpace(s.BaseUrl) ? "http://localhost:11434" : s.BaseUrl);
        return new OllamaApiClient(http, s.ModelId, null!); // JsonSerializerContext may be null
    }

    // Anthropic.SDK: HttpClient is the 2nd ctor arg; endpoint override via ApiUrlFormat template.
    private IChatClient CreateAnthropic(ChatSettings s, string? apiKey)
    {
        var client = new AnthropicClient(new APIAuthentication(apiKey!), Pooled(), requestInterceptor: null);
        if (!string.IsNullOrWhiteSpace(s.BaseUrl))
        {
            client.ApiUrlFormat = $"{s.BaseUrl.TrimEnd('/')}/{{0}}/{{1}}"; // "{base}/{version}/{endpoint}"
        }
        return client.Messages; // .Messages is the IChatClient
    }

    // Google.GenAI (official): HttpClient via a FACTORY on ClientOptions, not a direct param.
    private IChatClient CreateGemini(ChatSettings s, string? apiKey)
    {
        var clientOptions = new ClientOptions { HttpClientFactory = Pooled }; // Func<HttpClient>
        HttpOptions? http = string.IsNullOrWhiteSpace(s.BaseUrl) ? null : new HttpOptions { BaseUrl = s.BaseUrl };
        var client = new Client(
            enterprise: null, vertexAI: null, apiKey: apiKey,
            credential: null, project: null, location: null,
            httpOptions: http, clientOptions: clientOptions);
        return client.AsIChatClient(s.ModelId); // GoogleGenAIExtensions, in the Microsoft.Extensions.AI namespace
    }
}

Per-SDK injection cheat sheet

SDKWhere the shared HttpClient goesEndpoint override
OpenAI / Azure / compatibleOpenAIClientOptions.Transport = new HttpClientPipelineTransport(Pooled())OpenAIClientOptions.Endpoint
OllamaSharpnew OllamaApiClient(Pooled(), model, jsonCtx) (direct ctor arg)HttpClient.BaseAddress
Anthropic.SDKnew AnthropicClient(auth, Pooled(), interceptor) (2nd arg)client.ApiUrlFormat template
Google.GenAInew ClientOptions { HttpClientFactory = Pooled } (a Func<HttpClient>)HttpOptions.BaseUrl

MockChatClient.cs (account-less development)

namespace {Namespace}.Services;

internal sealed class MockChatClient : IChatClient
{
    public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
        IEnumerable<ChatMessage> messages, ChatOptions? options,
        [EnumeratorCancellation] CancellationToken ct = default)
    {
        const string reply = "This is a **mock** streamed reply.\n\n```csharp\nvar x = 1;\n```";
        foreach (string token in reply.Split(' '))
        {
            ct.ThrowIfCancellationRequested();
            yield return new ChatResponseUpdate(ChatRole.Assistant, token + " ");
            await Task.Delay(40, ct); // simulate token cadence
        }
    }

    public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages,
        ChatOptions? options, CancellationToken ct = default)
        => Task.FromResult(new ChatResponse(new ChatMessage(ChatRole.Assistant, "mock")));

    public object? GetService(Type serviceType, object? serviceKey = null) => null;
    public void Dispose() { }
}

Pair Provider.Mock with an orchestrator that skips MCP connection (empty tools) so the UI runs with no server at all.

Required: singleton lifetime

The shared handler is an instance field of the factory, so reuse depends on the same factory instance living for the app. Registering the factory transient/scoped creates a fresh SocketsHttpHandler (a fresh pool) on every resolve, silently defeating the pattern — no compile or runtime error.

// REQUIRED: one factory instance for the app's lifetime, so _shared is truly shared.
services.AddSingleton<I$0, $0>(); // GenericHost (CommunityToolkit.Mvvm)
// Prism: containerRegistry.RegisterSingleton<I$0, $0>();
// Transient/Scoped => new SocketsHttpHandler per resolve => no shared pool.

File Location

{Project}/
└── Services/
    ├── $0.cs
    ├── I$0.cs            (interface — or fold into $0.cs per project convention)
    ├── ChatSettings.cs
    ├── Provider.cs
    └── MockChatClient.cs

In a make-wpf-project solution (*.WpfApp + *.ViewModels), place the WPF-free contracts (I$0, ChatSettings, Provider) in *.ViewModels (namespace {Namespace}.ViewModels) so ViewModels can consume them without referencing the app project — this is how the one-button /wpf-dev-pack:make-wpf-chatclient lays them out. The implementation ($0, MockChatClient) stays in the app project's Services/.

Related

  • Knowledge (fetch via WpfDevPackMcp get_wpf_topic): sharing-httpclient-across-llm-sdks, hosting-extensions-ai-chatclient-in-wpf-mvvm, configuring-dependency-injection.
  • Sibling scaffolders: feeds /wpf-dev-pack:make-wpf-chat-orchestrator (which consumes the produced IChatClient). Both are emitted by the one-button /wpf-dev-pack:make-wpf-chatclient.

WPF Chat Client Generator (one-button)

If $0 is empty, use the AskUserQuestion tool to ask: "Enter the chat feature name (e.g., Chat, Assistant, Copilot)". Do NOT proceed until a valid name is provided. Use the response as the feature name for all subsequent steps.

This is the self-contained, one-button scaffolder: a single invocation emits an entire working streaming chat client and wires it into the app via ViewModel First (Mappings.xaml + DI). It composes the four component scaffolders and adds the glue (input behavior, auto-scroll behavior, view, view-model, DI) they don't cover. It defaults to a mock provider with no MCP, so the generated app builds and streams a reply with no API key and no server.

  • Replace {Namespace} with the project's root namespace, {Project} with the *.WpfApp path, and {ViewModels} with the *.ViewModels project.
  • Target app must be a make-wpf-project solution (.WpfApp + .ViewModels), CommunityToolkit.Mvvm + GenericHost. (Prism users: substitute BindableBase / DelegateCommand / RegisterForNavigation per view-viewmodel-wiring-prism.md.)

This skill is the one-button equivalent of running, in one pass, make-wpf-markdown-presenter + make-wpf-chat-bubble-template + make-wpf-chatclient-factory + make-wpf-chat-orchestrator, plus the view, view-model, and behaviors below. The full rationale for every piece lives in the knowledge topics listed under "Related".

⚠️ Verify SDK signatures with HandMirror before emitting provider/MCP code

The factory and orchestrator call version-sensitive APIs across several SDKs. Before emitting them, verify signatures with HandMirror (inspect_nuget_package / inspect_nuget_package_type): Microsoft.Extensions.AI, ModelContextProtocol, and any real providers you enable (OpenAI, OllamaSharp, Anthropic.SDK, Google.GenAI, System.ClientModel). The mock path needs none of these.

Workflow

Copy this checklist and emit each file in order:

ChatClient Scaffold Progress:
- [ ] 1. Packages: add PackageReferences to {ViewModels} AND {Project}; append GlobalUsings.cs in both
- [ ] 2. Components: emit MarkdownPresenter + ChatClientFactory(+Mock) into {Project}; ChatOrchestrator, ChatEvent, McpToolService, contracts into {ViewModels}
- [ ] 3. Behaviors: emit EnterCommandBehavior + StickToBottomBehavior
- [ ] 4. Turn VM: emit ChatTurnViewModel (IsUser, Markdown, IsWaiting)
- [ ] 5. Chat VM: emit IUiDispatcher + ChatViewModel ({ViewModels}) and WpfUiDispatcher ({Project})
- [ ] 6. View: emit ChatView.xaml (bubbles + input)
- [ ] 7. Wire: register DI (singleton factory + dispatcher + orchestrator + ChatViewModel), add Mappings.xaml entry
- [ ] 8. Verify: dotnet build; the mock provider streams a reply with no key

1. Required Packages + GlobalUsings

In {ViewModels} (*.ViewModels — orchestrator, events, contracts, and view-models live here; none of them touch WPF):

<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.*" />
<PackageReference Include="Microsoft.Extensions.AI" Version="10.*" />
<PackageReference Include="ModelContextProtocol" Version="1.*" />

Since ModelContextProtocol 1.x the CLIENT types (McpClient, StdioClientTransport, McpClientTool) live in the ModelContextProtocol.Core dependency; the ModelContextProtocol package itself carries server/DI types but pulls Core transitively, so the reference above still compiles the client code and the ModelContextProtocol.Client namespace is unchanged.

In {Project} (*.WpfApp — presenter, factory, behaviors, view; Microsoft.Extensions.AI flows transitively from the {ViewModels} project reference):

<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.*" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.*" />
<PackageReference Include="Markdig" Version="1.*" />
<!-- Real provider SDKs are optional; the default mock path needs none of them. -->

Append to {ViewModels} GlobalUsings.cs (the emitted code assumes these):

global using System.Collections.ObjectModel;
global using System.Runtime.CompilerServices;
global using CommunityToolkit.Mvvm.ComponentModel;
global using CommunityToolkit.Mvvm.Input;
global using Microsoft.Extensions.AI;
global using Microsoft.Extensions.Logging;
global using ModelContextProtocol.Client;

Append to {Project} GlobalUsings.cs:

global using System.Net.Http;
global using System.Runtime.CompilerServices;
global using System.Windows;
global using System.Windows.Controls;
global using System.Windows.Input;
global using Microsoft.Extensions.AI;
global using Microsoft.Xaml.Behaviors;

{Project} files that consume the contracts (ChatClientFactory.cs, WpfUiDispatcher.cs, App.xaml.cs) add a per-file using {Namespace}.ViewModels; — user-defined namespaces stay per-file, not in GlobalUsings.cs.

2. Components (emit using the canonical templates)

Emit these files now (this is what makes the skill self-contained — do not ask the user to run the component commands). Use the exact code from each component scaffolder / knowledge topic, with two overrides:

  • Placement/namespace override: files emitted into {ViewModels} use namespace {Namespace}.ViewModels; (not {Namespace}.Services); files in {Project} keep {Namespace}.Services / .Controls. The split keeps every WPF-free type in the UI-independent project — no circular reference, and mvvm-constraints.md stays satisfied.
  • Mock-only factory default: the factory's canonical template shows ALL provider arms. Emit only the Provider.Mock arm (others => throw new NotSupportedException($"Install and wire the {s.Provider} SDK first.")) unless the user asked for real providers — the default package set above contains no provider SDK, so emitting the full switch does not compile.
File(s)Target projectSource template
Controls/MarkdownPresenter.cs{Project}make-wpf-markdown-presenter
Services/ChatClientFactory.cs, Services/MockChatClient.cs{Project}make-wpf-chatclient-factory
IChatClientFactory.cs, ChatSettings.cs, Provider.cs{ViewModels}make-wpf-chatclient-factory (supporting types)
ChatOrchestrator.cs, ChatEvent.cs, McpToolService.cs{ViewModels}make-wpf-chat-orchestrator

3. Behaviors

Behaviors/EnterCommandBehavior.cs (Enter=send, Shift+Enter=newline, IME-safe)

namespace {Namespace}.Behaviors;

public sealed class EnterCommandBehavior : Behavior<TextBox>
{
    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register(nameof(Command), typeof(ICommand), typeof(EnterCommandBehavior), new(null));
    public ICommand? Command
    {
        get => (ICommand?)GetValue(CommandProperty);
        set => SetValue(CommandProperty, value);
    }

    public static readonly DependencyProperty CommandParameterProperty =
        DependencyProperty.Register(nameof(CommandParameter), typeof(object), typeof(EnterCommandBehavior), new(null));
    public object? CommandParameter
    {
        get => GetValue(CommandParameterProperty);
        set => SetValue(CommandParameterProperty, value);
    }

    protected override void OnAttached()  => AssociatedObject.PreviewKeyDown += OnPreviewKeyDown;
    protected override void OnDetaching() => AssociatedObject.PreviewKeyDown -= OnPreviewKeyDown;

    private void OnPreviewKeyDown(object sender, KeyEventArgs e)
    {
        // IME guard FIRST: an IME-composition confirm arrives as Key.ImeProcessed
        // (never Key.Enter), so it must not send. Checking Key.Enter first would
        // also skip it, but only by accident — keep the intent explicit.
        if (e.Key == Key.ImeProcessed) { return; }
        if (e.Key != Key.Enter) { return; }
        if ((Keyboard.Modifiers & ModifierKeys.Shift) != 0) { return; } // Shift+Enter -> newline (default)
        if (Command?.CanExecute(CommandParameter) == true) { Command.Execute(CommandParameter); }
        e.Handled = true;                                              // suppress the newline insert
    }
}

Behaviors/StickToBottomBehavior.cs (pin to newest unless scrolled up)

namespace {Namespace}.Behaviors;

public sealed class StickToBottomBehavior : Behavior<ScrollViewer>
{
    private bool _pinned = true;

    protected override void OnAttached()  => AssociatedObject.ScrollChanged += OnScrollChanged;
    protected override void OnDetaching() => AssociatedObject.ScrollChanged -= OnScrollChanged;

    private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
    {
        var sv = AssociatedObject;
        if (e.ExtentHeightChange == 0)
        {
            // user moved (no content growth): recompute whether we're at the bottom
            _pinned = sv.VerticalOffset >= sv.ScrollableHeight - 1.0;
        }
        else if (_pinned)
        {
            // content grew while pinned: follow it
            sv.ScrollToVerticalOffset(sv.ScrollableHeight);
        }
    }
}

4. ViewModels/ChatTurnViewModel.cs (one per turn)

namespace {Namespace}.ViewModels;

public sealed partial class ChatTurnViewModel : ObservableObject
{
    [ObservableProperty] private bool _isUser;
    [ObservableProperty] private bool _isWaiting;          // "waiting…" until the first token
    [ObservableProperty] private string _markdown = string.Empty;

    public void AppendMarkdown(string delta) => Markdown += delta;
}

5. ViewModels: IUiDispatcher + ChatViewModel (in {ViewModels}), WpfUiDispatcher (in {Project})

mvvm-constraints.md / P-002 ban System.Windows in ViewModel classes, and *.ViewModels is a plain classlib with no WPF reference — so the ViewModel must NOT call Application.Current.Dispatcher directly. Inject a one-method abstraction instead:

{ViewModels}/IUiDispatcher.cs

namespace {Namespace}.ViewModels;

public interface IUiDispatcher
{
    void Invoke(Action action);
}

{Project}/Services/WpfUiDispatcher.cs

namespace {Namespace}.Services;

public sealed class WpfUiDispatcher : IUiDispatcher
{
    public void Invoke(Action action) => Application.Current.Dispatcher.Invoke(action);
}

{ViewModels}/ChatViewModel.cs

namespace {Namespace}.ViewModels;

public sealed partial class ChatViewModel : ObservableObject
{
    private readonly ChatOrchestrator _orchestrator;
    private readonly IUiDispatcher _dispatcher;
    private readonly List<ChatMessage> _history = [];
    private CancellationTokenSource? _cts;
    private ChatTurnViewModel? _current;

    public ObservableCollection<ChatTurnViewModel> Turns { get; } = [];

    [NotifyCanExecuteChangedFor(nameof(SendCommand))]
    [ObservableProperty] private string _input = string.Empty;

    [NotifyCanExecuteChangedFor(nameof(SendCommand))]
    [NotifyCanExecuteChangedFor(nameof(StopCommand))]
    [ObservableProperty] private bool _isStreaming;

    public ChatViewModel(ChatOrchestrator orchestrator, IUiDispatcher dispatcher)
    {
        _orchestrator = orchestrator;
        _dispatcher = dispatcher;
    }

    private bool CanSend() => !IsStreaming && !string.IsNullOrWhiteSpace(Input);

    [RelayCommand(CanExecute = nameof(CanSend))]
    private async Task SendAsync()
    {
        string prompt = Input.Trim();
        Input = string.Empty;

        Turns.Add(new ChatTurnViewModel { IsUser = true, Markdown = prompt });
        _history.Add(new ChatMessage(ChatRole.User, prompt));

        _current = new ChatTurnViewModel { IsUser = false, IsWaiting = true };
        Turns.Add(_current);

        IsStreaming = true;
        _cts = new CancellationTokenSource();
        try
        {
            await foreach (ChatEvent ev in _orchestrator.SendAsync(_history, _cts.Token))
            {
                _dispatcher.Invoke(() => Apply(ev)); // marshal before touching bound state
            }
            _history.Add(new ChatMessage(ChatRole.Assistant, _current.Markdown));
        }
        catch (OperationCanceledException) { /* user pressed Stop — normal, not an error */ }
        finally
        {
            if (_current is not null) { _current.IsWaiting = false; }
            IsStreaming = false;
            _cts?.Dispose(); _cts = null;
        }
    }

    private bool CanStop() => IsStreaming;

    [RelayCommand(CanExecute = nameof(CanStop))]
    private void Stop() => _cts?.Cancel();

    private void Apply(ChatEvent ev)
    {
        switch (ev)
        {
            case ChatText t:     _current!.AppendMarkdown(t.Text); _current.IsWaiting = false; break;
            case ToolStarted s:  _current!.AppendMarkdown($"\n\n*Calling `{s.Name}`…*\n\n"); break;
            case ToolCompleted:  break; // optionally surface the tool result
            case ChatFailed f:   _current!.AppendMarkdown($"\n\n> {f.Error.Message}"); break;
        }
    }
}

ChatMessage/ChatRole come from Microsoft.Extensions.AI (installed in {ViewModels} in step 1); ChatOrchestrator/ChatEvent live in the same project (step 2 placement), so no extra ProjectReference is needed and the ViewModel stays free of System.Windows — the Dispatcher is reached only through IUiDispatcher, implemented WPF-side by WpfUiDispatcher.

6. Views/ChatView.xaml

<UserControl x:Class="{Namespace}.Views.ChatView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
             xmlns:behaviors="clr-namespace:{Namespace}.Behaviors"
             xmlns:controls="clr-namespace:{Namespace}.Controls"
             xmlns:vm="clr-namespace:{Namespace}.ViewModels;assembly={ViewModels}"
             mc:Ignorable="d"
             d:DataContext="{d:DesignInstance Type=vm:ChatViewModel}">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <!-- Conversation: pin-to-bottom unless the user scrolled up -->
        <ScrollViewer Grid.Row="0" VerticalScrollBarVisibility="Auto">
            <b:Interaction.Behaviors>
                <behaviors:StickToBottomBehavior/>
            </b:Interaction.Behaviors>
            <ItemsControl ItemsSource="{Binding Turns}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate DataType="{x:Type vm:ChatTurnViewModel}">
                        <Border Padding="10" CornerRadius="6">
                            <Border.Style>
                                <Style TargetType="Border">
                                    <!-- DEFAULT = ASSISTANT: left, neutral background, right gutter -->
                                    <Setter Property="HorizontalAlignment" Value="Left"/>
                                    <Setter Property="Margin" Value="0,4,48,0"/>
                                    <Setter Property="Background" Value="#FFF0F0F0"/>
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding IsUser}" Value="True">
                                            <!-- USER: right, tinted background, left gutter -->
                                            <Setter Property="HorizontalAlignment" Value="Right"/>
                                            <Setter Property="Margin" Value="48,4,0,0"/>
                                            <Setter Property="Background" Value="#FFD6E8FF"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Border.Style>
                            <controls:MarkdownPresenter Markdown="{Binding Markdown}"/>
                        </Border>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </ScrollViewer>

        <!-- Input: Enter=send, Shift+Enter=newline -->
        <Grid Grid.Row="1" Margin="0,8,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <TextBox Grid.Column="0" AcceptsReturn="True" MaxLines="4"
                     Text="{Binding Input, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                <b:Interaction.Behaviors>
                    <behaviors:EnterCommandBehavior Command="{Binding SendCommand}"/>
                </b:Interaction.Behaviors>
            </TextBox>
            <Button Grid.Column="1" Margin="6,0,0,0" Content="Send" Command="{Binding SendCommand}"/>
            <Button Grid.Column="2" Margin="6,0,0,0" Content="Stop" Command="{Binding StopCommand}"/>
        </Grid>
    </Grid>
</UserControl>
namespace {Namespace}.Views;

public partial class ChatView : UserControl
{
    public ChatView() => InitializeComponent();
}

The default uses stock-WPF brushes so the view builds with no UI-kit package. If (and only if) the app already references WPF-UI (Wpf.Ui), you may swap the two Background Setters for the {ui:ThemeResource ...} variant in make-wpf-chat-bubble-template — adding xmlns:ui without the package is an MC3074 build error, and an invalid theme-resource key throws at render time, not at build.

7. Wire DI + Mappings.xaml (ViewModel First)

In App.xaml.cs ConfigureServices — the factory MUST be a singleton (shared HttpClient pool), and the default settings use Provider.Mock so it runs keyless:

// Shared HttpClient pool — singleton is part of the pattern's correctness.
services.AddSingleton<IChatClientFactory, ChatClientFactory>();
services.AddSingleton<IUiDispatcher, WpfUiDispatcher>();

services.AddSingleton(sp =>
{
    var settings = new ChatSettings { Provider = Provider.Mock, ModelId = "mock" };
    IChatClient client = sp.GetRequiredService<IChatClientFactory>().Create(settings, apiKey: null);
    return new ChatOrchestrator(client, tools: [], settings); // no MCP tools in the mock default
});

services.AddSingleton<ChatViewModel>();

Append one entry to Mappings.xaml (the View is resolved from the ViewModel type — no x:Key, ViewModel First; ViewModelLocator / code-behind DataContext are prohibited, see prohibitions.md):

<DataTemplate DataType="{x:Type vm:ChatViewModel}">
    <views:ChatView />
</DataTemplate>

Show the chat by assigning the shell's CurrentViewModel: CurrentViewModel = host.Services.GetRequiredService<ChatViewModel>();

8. Going live (beyond the mock)

  • Real provider: change ChatSettings.Provider/ModelId/BaseUrl, and pass the API key from the OS credential store — never config. See storing-api-keys-and-binding-passwordbox-in-wpf (and bind the key field with the attached behavior, since PasswordBox.Password is not a DP).
  • Settings UI: a provider/model/BaseURL/key panel with per-provider conditional fields is covered by building-a-provider-settings-panel.
  • MCP tools: call McpToolService.ConnectAsync(...) once at startup and pass [.. mcpToolService.Tools] into the ChatOrchestrator; dispose it OFF the Dispatcher in App.OnExit (consuming-mcp-tools-in-extensions-ai).
  • Long histories: virtualize the conversation list — see the variable-height selectable-bubble caveats in virtualizing-wpf-ui.

File Location

{Project} (*.WpfApp)/
├── Behaviors/
│   ├── EnterCommandBehavior.cs
│   └── StickToBottomBehavior.cs
├── Controls/
│   └── MarkdownPresenter.cs
├── Services/
│   ├── ChatClientFactory.cs
│   ├── MockChatClient.cs
│   └── WpfUiDispatcher.cs
├── Views/
│   ├── ChatView.xaml
│   └── ChatView.xaml.cs
└── Mappings.xaml              (+1 DataTemplate)
{ViewModels} (*.ViewModels)/    ← WPF-free: namespace {Namespace}.ViewModels
├── ChatViewModel.cs
├── ChatTurnViewModel.cs
├── IUiDispatcher.cs
├── ChatOrchestrator.cs
├── ChatEvent.cs
├── McpToolService.cs
├── IChatClientFactory.cs
├── ChatSettings.cs
└── Provider.cs

Related

  • Component scaffolders: /wpf-dev-pack:make-wpf-markdown-presenter, /wpf-dev-pack:make-wpf-chat-bubble-template, /wpf-dev-pack:make-wpf-chatclient-factory, /wpf-dev-pack:make-wpf-chat-orchestrator, /wpf-dev-pack:make-wpf-behavior (the two behaviors above are instances of it).
  • Knowledge (fetch via WpfDevPackMcp get_wpf_topic): rendering-markdown-in-wpf, displaying-selectable-rich-text-in-wpf, styling-chat-bubbles-in-wpf, hosting-extensions-ai-chatclient-in-wpf-mvvm, sharing-httpclient-across-llm-sdks, consuming-mcp-tools-in-extensions-ai, storing-api-keys-and-binding-passwordbox-in-wpf, building-a-provider-settings-panel, virtualizing-wpf-ui.

WPF Converter Generator

If $0 is empty, use the AskUserQuestion tool to ask: "Enter the Converter name (e.g., BoolToVisibility, NullToVisibility)". Do NOT proceed until a valid name is provided. Use the response as the ConverterName for all subsequent steps.

Generate a $0Converter class with MarkupExtension pattern for direct XAML usage. If multi is appended to the arguments, generate IMultiValueConverter instead of IValueConverter.

  • Replace {Namespace} with the project's root namespace detected from csproj or existing code.
  • Replace {SourceType} and {TargetType} with the appropriate types based on the converter name (e.g., BoolToVisibility → bool, Visibility).
  • Replace {Project} with the target project path.

Usage

# IValueConverter
/wpf-dev-pack:make-wpf-converter BoolToVisibility

# IMultiValueConverter
/wpf-dev-pack:make-wpf-converter AllTrue multi

Generated Code

Base Class (ConverterMarkupExtension.cs)

Create this base class first in your Converters folder:

namespace {Namespace}.Converters;

/// <summary>
/// Base class for converters that can be used directly in XAML without resource declaration.
/// </summary>
public abstract class ConverterMarkupExtension<T> : MarkupExtension, IValueConverter
    where T : class, new()
{
    private static readonly Lazy<T> _converter = new(() => new T());

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return _converter.Value;
    }

    public abstract object? Convert(
        object? value,
        Type targetType,
        object? parameter,
        CultureInfo culture);

    public virtual object? ConvertBack(
        object? value,
        Type targetType,
        object? parameter,
        CultureInfo culture)
    {
        throw new NotSupportedException("ConvertBack is not supported.");
    }
}

Base Class (MultiConverterMarkupExtension.cs)

namespace {Namespace}.Converters;

/// <summary>
/// Base class for multi-value converters with MarkupExtension support.
/// </summary>
public abstract class MultiConverterMarkupExtension<T> : MarkupExtension, IMultiValueConverter
    where T : class, new()
{
    private static readonly Lazy<T> _converter = new(() => new T());

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return _converter.Value;
    }

    public abstract object? Convert(
        object?[] values,
        Type targetType,
        object? parameter,
        CultureInfo culture);

    public virtual object?[] ConvertBack(
        object? value,
        Type[] targetTypes,
        object? parameter,
        CultureInfo culture)
    {
        throw new NotSupportedException("ConvertBack is not supported.");
    }
}

IValueConverter

namespace {Namespace}.Converters;

/// <summary>
/// Converts {SourceType} to {TargetType}.
/// </summary>
public sealed class $0Converter : ConverterMarkupExtension<$0Converter>
{
    public override object? Convert(
        object? value,
        Type targetType,
        object? parameter,
        CultureInfo culture)
    {
        // TODO: Implement conversion logic
        if (value is not {SourceType} source)
        {
            return DependencyProperty.UnsetValue;
        }

        return source; // Replace with actual conversion
    }
}

IMultiValueConverter

namespace {Namespace}.Converters;

/// <summary>
/// Combines multiple values into a single result.
/// </summary>
public sealed class $0Converter : MultiConverterMarkupExtension<$0Converter>
{
    public override object? Convert(
        object?[] values,
        Type targetType,
        object? parameter,
        CultureInfo culture)
    {
        // Validate input values
        if (values is null || values.Length < 2)
        {
            return DependencyProperty.UnsetValue;
        }

        // Check for unset values
        if (values.Any(v => v == DependencyProperty.UnsetValue))
        {
            return DependencyProperty.UnsetValue;
        }

        // TODO: Implement multi-value conversion logic
        return values;
    }
}

XAML Usage

MarkupExtension Pattern (Recommended)

<Window xmlns:conv="clr-namespace:MyApp.Converters">
    <!-- No resource declaration needed! -->
    <TextBlock Visibility="{Binding IsVisible, Converter={conv:BoolToVisibilityConverter}}"/>

    <!-- With parameter -->
    <TextBlock Visibility="{Binding IsHidden, Converter={conv:BoolToVisibilityConverter}, ConverterParameter=Invert}"/>
</Window>

MultiBinding

<TextBlock>
    <TextBlock.Text>
        <MultiBinding Converter="{conv:FullNameConverter}">
            <Binding Path="FirstName"/>
            <Binding Path="LastName"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Common Converters

BoolToVisibilityConverter

public sealed class BoolToVisibilityConverter : ConverterMarkupExtension<BoolToVisibilityConverter>
{
    public override object? Convert(
        object? value,
        Type targetType,
        object? parameter,
        CultureInfo culture)
    {
        if (value is not bool boolValue)
            return Visibility.Collapsed;

        var invert = parameter is "Invert" or "invert";
        return (boolValue ^ invert) ? Visibility.Visible : Visibility.Collapsed;
    }
}

NullToVisibilityConverter

public sealed class NullToVisibilityConverter : ConverterMarkupExtension<NullToVisibilityConverter>
{
    public override object? Convert(
        object? value,
        Type targetType,
        object? parameter,
        CultureInfo culture)
    {
        var isNull = value is null;
        var invert = parameter is "Invert";
        return (isNull ^ invert) ? Visibility.Collapsed : Visibility.Visible;
    }
}

InverseBoolConverter

public sealed class InverseBoolConverter : ConverterMarkupExtension<InverseBoolConverter>
{
    public override object? Convert(
        object? value,
        Type targetType,
        object? parameter,
        CultureInfo culture)
    {
        if (value is not bool boolValue)
            return false;

        return !boolValue;
    }

    public override object? ConvertBack(
        object? value,
        Type targetType,
        object? parameter,
        CultureInfo culture)
    {
        if (value is not bool boolValue)
            return false;

        return !boolValue;
    }
}

File Structure

{Project}/
└── Converters/
    ├── ConverterMarkupExtension.cs       # Base class
    ├── MultiConverterMarkupExtension.cs  # Multi base class
    ├── BoolToVisibilityConverter.cs
    ├── NullToVisibilityConverter.cs
    └── $0Converter.cs

GlobalUsings.cs

Append these to the project's existing GlobalUsings.cs (do not create a second one — duplicate global using directives fail to compile):

global using System;
global using System.Globalization;
global using System.Linq;
global using System.Windows;
global using System.Windows.Data;
global using System.Windows.Markup;

Comparison: StaticResource vs MarkupExtension

AspectStaticResourceMarkupExtension
Resource declarationRequiredNot required
XAML usage{StaticResource Key}{local:Converter}
SingletonManualBuilt-in (Lazy)
BoilerplateMoreLess

Related knowledge topics (via WpfDevPackMcp)

Fetch with WpfDevPackMcp get_wpf_topic:

  • using-converter-markup-extension — detailed MarkupExtension pattern (the canonical converter pattern)
  • advanced-data-binding — MultiBinding patterns

Plugin rule: wpf-rule-converter-patterns skill — MarkupExtension singleton, null/UnsetValue handling, TemplateBinding guidance.

WPF CustomControl Generation

If $0 is empty, use the AskUserQuestion tool to ask: "Enter the CustomControl name (e.g., CircularProgress, RangeSlider)". Do NOT proceed until a valid name is provided. Use the response as the ControlName for all subsequent steps.

Generate a $0 CustomControl.

  • Replace {BaseClass} with the appropriate WPF base class (e.g., Control, Button, ContentControl, ItemsControl) based on the control name and context.
  • Replace {Namespace} with the project's root namespace detected from csproj or existing code.
  • If the host project follows a non-default style convention (e.g. block-scoped namespaces, custom usings), conform to it.

Workflow

Step 1: Validate Input

  • $0 must be PascalCase
  • Determine the best BaseClass based on $0 name and intended usage

Step 2: Generate C# Class File

Create $0.cs:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;

namespace {Namespace}.Controls;

/// <summary>
/// $0 - Custom WPF control based on {BaseClass}.
/// </summary>
[TemplatePart(Name = TemplateParts.Root, Type = typeof(Border))]
[TemplateVisualState(GroupName = VisualStates.CommonStates, Name = VisualStates.Normal)]
[TemplateVisualState(GroupName = VisualStates.CommonStates, Name = VisualStates.MouseOver)]
[TemplateVisualState(GroupName = VisualStates.CommonStates, Name = VisualStates.Pressed)]
[TemplateVisualState(GroupName = VisualStates.CommonStates, Name = VisualStates.Disabled)]
public class $0 : {BaseClass}
{
    // Single source of truth for Template Part names.
    // XAML <Border x:Name="…"> literals MUST match these constants.
    private static class TemplateParts
    {
        public const string Root = "PART_Root";
    }

    // Single source of truth for VSM group/state names.
    // XAML <VisualStateGroup x:Name="…"> / <VisualState x:Name="…"> literals
    // MUST match these constants exactly. The compiler will not catch a mismatch
    // and runtime GoToState will return false silently.
    private static class VisualStates
    {
        public const string CommonStates = "CommonStates";
        public const string Normal       = "Normal";
        public const string MouseOver    = "MouseOver";
        public const string Pressed      = "Pressed";
        public const string Disabled     = "Disabled";
    }

    #region Constructors

    static $0()
    {
        DefaultStyleKeyProperty.OverrideMetadata(
            typeof($0),
            new FrameworkPropertyMetadata(typeof($0)));
    }

    public $0()
    {
        // IsEnabledChanged is an EVENT — there is no OnIsEnabledChanged to
        // override (Control/UIElement exposes no such virtual). Subscribe here.
        IsEnabledChanged += (_, _) => UpdateVisualState(true);
    }

    #endregion

    #region Dependency Properties

    /// <summary>
    /// Example dependency property.
    /// </summary>
    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register(
            nameof(Value),
            typeof(int),
            typeof($0),
            new FrameworkPropertyMetadata(
                defaultValue: 0,
                flags: FrameworkPropertyMetadataOptions.AffectsRender,
                propertyChangedCallback: OnValueChanged,
                coerceValueCallback: CoerceValue));

    public int Value
    {
        get => (int)GetValue(ValueProperty);
        set => SetValue(ValueProperty, value);
    }

    private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is $0 control)
        {
            control.OnValueChanged((int)e.OldValue, (int)e.NewValue);
        }
    }

    protected virtual void OnValueChanged(int oldValue, int newValue)
    {
        // Handle property change
    }

    // Multi-constraint coerce: relational constraints first, hard domain LAST.
    // See authoring-wpf-controls §4 "Multi-Constraint Coerce Ordering".
    private static object CoerceValue(DependencyObject d, object baseValue)
    {
        var control = ($0)d;
        var v = (int)baseValue;

        // (Add any relational constraints that depend on other properties first.)

        // Hard domain clamp LAST so transient cross-property states cannot leak
        // a value outside the legal domain.
        v = Math.Clamp(v, 0, 100);

        return v;
    }

    #endregion

    #region Read-only Dependency Property (optional)

    // Read-only DPs expose internal state for binding while preventing external writes.
    // Replace with your real read-only property or remove this region.
    private static readonly DependencyPropertyKey IsBusyPropertyKey =
        DependencyProperty.RegisterReadOnly(
            nameof(IsBusy),
            typeof(bool),
            typeof($0),
            new PropertyMetadata(false));

    public static readonly DependencyProperty IsBusyProperty = IsBusyPropertyKey.DependencyProperty;

    public bool IsBusy
    {
        get => (bool)GetValue(IsBusyProperty);
        private set => SetValue(IsBusyPropertyKey, value);
    }

    #endregion

    #region Routed Event (optional)

    // Replace with your real routed event or remove this region.
    public static readonly RoutedEvent ValueChangedEvent =
        EventManager.RegisterRoutedEvent(
            nameof(ValueChanged),
            RoutingStrategy.Bubble,
            typeof(RoutedPropertyChangedEventHandler<int>),
            typeof($0));

    public event RoutedPropertyChangedEventHandler<int> ValueChanged
    {
        add    => AddHandler(ValueChangedEvent, value);
        remove => RemoveHandler(ValueChangedEvent, value);
    }

    protected virtual void OnValueChanged(RoutedPropertyChangedEventArgs<int> e)
        => RaiseEvent(e);

    #endregion

    #region Template Parts

    private Border? _partRoot;
    private bool _isPressed;

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        // OnApplyTemplate fires BEFORE Loaded. Avoid duplicating init logic in both —
        // do template-binding setup here, and only do Loaded-time work in Loaded.
        _partRoot = GetTemplateChild(TemplateParts.Root) as Border;

        // Template-Part tolerance: if PART_Root is missing, disable only the
        // feature that depends on it. Do NOT throw — see authoring-wpf-controls §3.1.
        if (_partRoot is null)
        {
            // Optional: log a designer-only warning here if you want.
        }

        UpdateVisualState(false);
    }

    #endregion

    #region Visual States

    private void UpdateVisualState(bool useTransitions)
    {
        // States declared via [TemplateVisualState] MUST be reachable here,
        // otherwise the attribute is a documentation lie and the state never fires.
        string state =
            !IsEnabled  ? VisualStates.Disabled  :
            _isPressed  ? VisualStates.Pressed   :
            IsMouseOver ? VisualStates.MouseOver :
                          VisualStates.Normal;

        VisualStateManager.GoToState(this, state, useTransitions);
    }

    protected override void OnMouseEnter(MouseEventArgs e)
    {
        base.OnMouseEnter(e);
        UpdateVisualState(true);
    }

    protected override void OnMouseLeave(MouseEventArgs e)
    {
        base.OnMouseLeave(e);
        UpdateVisualState(true);
    }

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonDown(e);
        _isPressed = true;
        UpdateVisualState(true);
    }

    protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonUp(e);
        _isPressed = false;
        UpdateVisualState(true);
    }

    // Note: IsEnabled changes are handled via the IsEnabledChanged event
    // subscribed in the constructor (there is no OnIsEnabledChanged to override).

    #endregion
}

Step 3: Generate XAML Style File

Create Themes/$0.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:{Namespace}.Controls">

    <!--
        Color/brush resources.
        Prefer host theme tokens (ThemeResource / implicit Style) for colors that
        should follow the host app's theme; use signature-only x:Key brushes
        for colors that uniquely identify THIS control's visual identity.
        Hard-coded hex values like below are placeholders.
    -->
    <SolidColorBrush x:Key="$0DefaultBackground"      Color="#FFFFFF" />
    <SolidColorBrush x:Key="$0DefaultForeground"     Color="#000000" />
    <SolidColorBrush x:Key="$0DefaultBorderBrush"    Color="#CCCCCC" />
    <SolidColorBrush x:Key="$0MouseOverOverlayBrush" Color="#1A2196F3" />
    <SolidColorBrush x:Key="$0PressedOverlayBrush"   Color="#332196F3" />

    <Style TargetType="{x:Type local:$0}">
        <Setter Property="Background"   Value="{StaticResource $0DefaultBackground}" />
        <Setter Property="Foreground"   Value="{StaticResource $0DefaultForeground}" />
        <Setter Property="BorderBrush"  Value="{StaticResource $0DefaultBorderBrush}" />
        <Setter Property="BorderThickness" Value="1" />
        <Setter Property="Padding"      Value="8,4" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:$0}">

                    <!--
                        x:Name literals MUST match the const TemplateParts/VisualStates
                        on the C# side ($0.cs). VSM is a name-based contract: a
                        mismatch is a silent runtime no-op.
                    -->
                    <Border x:Name="PART_Root"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Padding="{TemplateBinding Padding}"
                            CornerRadius="4">

                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal" />

                                <!--
                                    Animate Opacity of a dedicated overlay layer instead of
                                    (Border.Background).(SolidColorBrush.Color). The latter
                                    explodes silently if Background is a shared/frozen
                                    brush (e.g. from a theme dictionary) or a DynamicResource.
                                -->
                                <VisualState x:Name="MouseOver">
                                    <Storyboard>
                                        <DoubleAnimation
                                            Storyboard.TargetName="PART_MouseOverOverlay"
                                            Storyboard.TargetProperty="Opacity"
                                            To="1.0"
                                            Duration="0:0:0.15" />
                                    </Storyboard>
                                </VisualState>

                                <VisualState x:Name="Pressed">
                                    <Storyboard>
                                        <DoubleAnimation
                                            Storyboard.TargetName="PART_PressedOverlay"
                                            Storyboard.TargetProperty="Opacity"
                                            To="1.0"
                                            Duration="0:0:0.10" />
                                    </Storyboard>
                                </VisualState>

                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <DoubleAnimation
                                            Storyboard.TargetName="PART_Root"
                                            Storyboard.TargetProperty="Opacity"
                                            To="0.5"
                                            Duration="0:0:0" />
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>

                        <Grid>
                            <!-- MouseOver / Pressed overlays: each is an opaque-controllable
                                 layer that animates Opacity, not the underlying brush color. -->
                            <Border x:Name="PART_MouseOverOverlay"
                                    Background="{StaticResource $0MouseOverOverlayBrush}"
                                    CornerRadius="4"
                                    Opacity="0"
                                    IsHitTestVisible="False" />
                            <Border x:Name="PART_PressedOverlay"
                                    Background="{StaticResource $0PressedOverlayBrush}"
                                    CornerRadius="4"
                                    Opacity="0"
                                    IsHitTestVisible="False" />

                            <ContentPresenter
                                HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Step 4: Ensure a CustomControl home, then register the theme

CustomControls require a Themes/Generic.xaml and the ThemeInfo assembly attribute. Prefer a dedicated .UI CustomControl library; if the solution has none, target the WPF app project and create the infrastructure there.

4a. If Themes/Generic.xaml does not exist in the target project, create it as a hub-only dictionary (see resourcedictionary-patterns.md — hub only, no inline styles):

<!-- Themes/Generic.xaml -->
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/Themes/$0.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

4b. If the ThemeInfo attribute is missing, add it once (e.g. in Properties/AssemblyInfo.cs or any .cs) so WPF locates Generic.xaml:

using System.Windows;

[assembly: ThemeInfo(
    ResourceDictionaryLocation.None,
    ResourceDictionaryLocation.SourceAssembly)]

4c. If Generic.xaml already exists, just add this control's dictionary to its MergedDictionaries:

<ResourceDictionary.MergedDictionaries>
    <!-- Existing entries -->
    <ResourceDictionary Source="/Themes/$0.xaml" />
</ResourceDictionary.MergedDictionaries>

Output Summary

After generation, provide:

  1. Created files list
  2. Next steps for customization (which DPs/events to keep, which to remove)
  3. Usage example in XAML
<!-- Usage Example -->
<local:$0 Value="42" />

Related knowledge topics (via WpfDevPackMcp)

Fetch with WpfDevPackMcp get_wpf_topic:

  • authoring-wpf-controls — §3.4 Visual State Naming Contract, §4 Multi-Constraint Coerce Ordering, §3.1 Template-Part tolerance
  • animating-wpf-controltemplates — the <Storyboard> bodies + VisualStateGroup.Transitions that fill the VisualStates above; ambient loops; the Setter-on-Freezable (MC4111), inline-animated-brush, and StaticResource-forward-reference pitfalls; verify-at-runtime harness
  • containing-control-decorative-overflow — when focus ring / hover glow gets clipped at an ancestor boundary
  • managing-styles-resourcedictionary — Generic.xaml hub pattern
  • managing-literal-strings — consolidating literal strings (VSM names are a notable WPF-specific case)

WPF Markdown Presenter Generator

If $0 is empty, use the AskUserQuestion tool to ask: "Enter the presenter control name (e.g., MarkdownPresenter, ChatMarkdownView)". Do NOT proceed until a valid name is provided. Use the response as the control name for all subsequent steps.

Generate a $0 control: a ContentControl with a bindable Markdown dependency property that parses markdown with Markdig, builds a WPF FlowDocument, and hosts it in a selectable, content-hugging read-only RichTextBox.

  • Replace {Namespace} with the project's root namespace detected from csproj or existing code.
  • Replace {Project} with the target project path (a WPF Application or WPF control library — must have UseWPF).

The full rationale for every choice below is in two knowledge topics — fetch with WpfDevPackMcp get_wpf_topic: rendering-markdown-in-wpf (the AST→FlowDocument dispatcher, the "never ToString() a node" rule, the Block/Inline aliasing, Hyperlink scheme validation) and displaying-selectable-rich-text-in-wpf (the read-only RichTextBox host, the content-hugging HuggingRichTextBox, MouseWheel forwarding, streaming throttle).

Usage

/wpf-dev-pack:make-wpf-markdown-presenter MarkdownPresenter

Required Packages

<PackageReference Include="Markdig" Version="1.*" />
  • Markdig is required (markdown parsing). Verify the current version and the exact API surface with HandMirror before emitting (inspect_nuget_package / inspect_nuget_package_type on Markdig), since the AST node type names drive the switch.
  • The code uses the WPF-UI (Wpf.Ui) theme-brush keys TextFillColorPrimaryBrush / TextFillColorSecondaryBrush via SetResourceReference, and a Wpf.Ui.Controls.Button for the code-block Copy button. If WPF-UI is not installed, swap those for stock WPF (SystemColors.ControlTextBrushKey resource reference, and a plain System.Windows.Controls.Button). See integrating-wpfui-fluent for the brush keys.

Generated Code

$0.cs

The three using-aliases at the top are mandatory — Markdig.Syntax.Block and System.Windows.Documents.Block (and the two Inline types) collide (CS0104), so both must be aliased in any file that both parses markdown and builds a FlowDocument.

using System.Diagnostics;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Markdig;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;

using MarkdigBlock  = Markdig.Syntax.Block;            // markdown AST node
using MarkdigInline = Markdig.Syntax.Inlines.Inline;   // markdown AST inline
using FlowBlock     = System.Windows.Documents.Block;  // FlowDocument node

namespace {Namespace}.Controls;

/// <summary>
/// A ContentControl that renders a bound Markdown string as a selectable WPF
/// FlowDocument hosted in a read-only RichTextBox. Unhandled Markdig AST nodes
/// are recursed (Container), degraded to inlines/lines (Leaf), or skipped —
/// never ToString()'d (the default ToString returns the type name).
/// </summary>
public sealed class $0 : ContentControl
{
    private static readonly MarkdownPipeline _pipeline =
        new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();

    public static readonly DependencyProperty MarkdownProperty =
        DependencyProperty.Register(nameof(Markdown), typeof(string), typeof($0),
            new PropertyMetadata(null, OnMarkdownChanged));

    public string? Markdown
    {
        get => (string?)GetValue(MarkdownProperty);
        set => SetValue(MarkdownProperty, value);
    }

    // Coalesce re-renders during fast streaming instead of rebuilding per token.
    private readonly DispatcherTimer _renderTimer =
        new() { Interval = TimeSpan.FromMilliseconds(50) }; // ~20 Hz

    public $0()
    {
        _renderTimer.Tick += (_, _) => { _renderTimer.Stop(); Render(Markdown); };
    }

    private static void OnMarkdownChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var self = ($0)d;
        self._renderTimer.Stop();
        self._renderTimer.Start(); // debounce: render once the burst settles
    }

    // Render: parse markdown -> build a FlowDocument -> host it in a read-only RichTextBox.
    private void Render(string? markdown)
    {
        if (string.IsNullOrEmpty(markdown)) { Content = null; return; }

        var doc = new FlowDocument { PagePadding = new Thickness(0), FontSize = 14 };
        foreach (MarkdigBlock block in Markdig.Markdown.Parse(markdown, _pipeline))
        {
            FlowBlock? b = RenderBlock(block);
            if (b is not null) { doc.Blocks.Add(b); }
        }

        var host = new HuggingRichTextBox
        {
            Document = doc,
            IsReadOnly = true,          // selection + Ctrl+C; no editing, no caret
            IsDocumentEnabled = true,   // Hyperlink inlines stay clickable
            IsTabStop = false,
            BorderThickness = new Thickness(0),
            Background = Brushes.Transparent,
            Padding = new Thickness(0),
            MinHeight = 0,
            NaturalWidth = ComputeNaturalWidth(markdown)
        };
        // Code-built text elements do NOT inherit a theme foreground — set it once.
        host.SetResourceReference(Control.ForegroundProperty, "TextFillColorPrimaryBrush");
        ScrollViewer.SetHorizontalScrollBarVisibility(host, ScrollBarVisibility.Disabled); // wrap at forced width
        host.PreviewMouseWheel += ForwardWheelToParent;
        Content = host;
    }

    private FlowBlock? RenderBlock(MarkdigBlock block) => block switch
    {
        FencedCodeBlock c   => BuildCodeBlock(c.Lines.ToString()),
        CodeBlock c         => BuildCodeBlock(c.Lines.ToString()),
        HeadingBlock h      => BuildHeading(h),
        ListBlock l         => BuildList(l),
        QuoteBlock q        => BuildQuote(q),
        ThematicBreakBlock  => BuildThematicBreak(),
        ParagraphBlock p    => BuildParagraph(p),
        ContainerBlock c    => BuildContainerFallback(c), // recurse children into a Section
        LeafBlock leaf      => BuildLeafFallback(leaf),   // render its inlines/lines
        _ => null,                                        // never emit a type name
    };

    private Paragraph BuildParagraph(ParagraphBlock p)
    {
        var para = new Paragraph { Margin = new Thickness(0, 0, 0, 6) };
        AppendInlines(para.Inlines, p.Inline);
        return para;
    }

    private Paragraph BuildHeading(HeadingBlock h)
    {
        var para = new Paragraph
        {
            FontWeight = FontWeights.Bold,
            FontSize = h.Level switch { 1 => 20, 2 => 17, 3 => 15, _ => 14 },
            Margin = new Thickness(0, 0, 0, 6)
        };
        AppendInlines(para.Inlines, h.Inline);
        return para;
    }

    private Section BuildQuote(QuoteBlock quote)
    {
        var section = new Section
        {
            BorderThickness = new Thickness(3, 0, 0, 0),   // left accent rule
            Padding = new Thickness(8, 0, 0, 0),
            Margin = new Thickness(0, 0, 0, 6)
        };
        section.SetResourceReference(TextElement.ForegroundProperty, "TextFillColorSecondaryBrush");
        section.SetResourceReference(FlowBlock.BorderBrushProperty, "TextFillColorSecondaryBrush");
        foreach (MarkdigBlock child in quote)
        {
            FlowBlock? r = RenderBlock(child);
            if (r is not null) { section.Blocks.Add(r); }
        }
        return section;
    }

    private List BuildList(ListBlock list)
    {
        var result = new List
        {
            MarkerStyle = list.IsOrdered ? TextMarkerStyle.Decimal : TextMarkerStyle.Disc,
            Margin = new Thickness(0, 0, 0, 6),
            Padding = new Thickness(16, 0, 0, 0)
        };
        foreach (MarkdigBlock item in list)
        {
            var li = new ListItem();
            if (item is ListItemBlock ib)
            {
                foreach (MarkdigBlock child in ib)
                {
                    FlowBlock? r = RenderBlock(child);
                    if (r is not null) { li.Blocks.Add(r); }
                }
            }
            if (li.Blocks.Count == 0) { li.Blocks.Add(new Paragraph(new Run(item.ToString() ?? string.Empty))); }
            result.ListItems.Add(li);
        }
        return result;
    }

    // Generic fallbacks — the anti-type-name-leak core:
    private Section BuildContainerFallback(ContainerBlock container)
    {
        var s = new Section();
        foreach (MarkdigBlock child in container)
        {
            FlowBlock? r = RenderBlock(child);
            if (r is not null) { s.Blocks.Add(r); }
        }
        return s;
    }

    private Paragraph BuildLeafFallback(LeafBlock leaf)
    {
        var p = new Paragraph { Margin = new Thickness(0, 0, 0, 6) };
        if (leaf.Inline is not null) { AppendInlines(p.Inlines, leaf.Inline); }
        else { p.Inlines.Add(new Run(leaf.Lines.ToString())); }
        return p;
    }

    // A horizontal rule. Minimal helper — adjust styling as needed.
    private static FlowBlock BuildThematicBreak()
        => new BlockUIContainer(new Separator { Margin = new Thickness(0, 4, 0, 4) });

    private static BlockUIContainer BuildCodeBlock(string code)
    {
        string text = code.TrimEnd('\n', '\r');
        var box = new TextBox
        {
            Text = text, IsReadOnly = true,
            FontFamily = new FontFamily("Consolas"),
            TextWrapping = TextWrapping.NoWrap,
            HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
            BorderThickness = new Thickness(0), Background = Brushes.Transparent
        };
        box.SetResourceReference(TextBox.ForegroundProperty, "TextFillColorPrimaryBrush");
        var copy = new Button { Content = "Copy", VerticalAlignment = VerticalAlignment.Top };
        copy.Click += (_, _) => { try { Clipboard.SetText(text); } catch { /* clipboard busy */ } };

        var grid = new Grid();
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        Grid.SetColumn(box, 0); Grid.SetColumn(copy, 1);
        grid.Children.Add(box); grid.Children.Add(copy);

        var border = new Border { Padding = new Thickness(8), Margin = new Thickness(0, 4, 0, 6), Child = grid };
        return new BlockUIContainer(border) { Margin = new Thickness(0) };
    }

    private void AppendInlines(InlineCollection target, ContainerInline? container)
    {
        if (container is null) { return; }
        foreach (MarkdigInline inline in container)
        {
            switch (inline)
            {
                case LiteralInline lit:
                    target.Add(new Run(lit.Content.ToString()));
                    break;
                case EmphasisInline em:
                    Span span;
                    if (em.DelimiterCount >= 2) { span = new Bold(); } else { span = new Italic(); }
                    AppendInlines(span.Inlines, em);   // nested formatting preserved
                    target.Add(span);
                    break;
                case CodeInline code:
                    target.Add(new Run(code.Content) { FontFamily = new FontFamily("Consolas") });
                    break;
                case LinkInline link:
                    var h = new Hyperlink { NavigateUri = SafeUri(link.Url) };
                    AppendInlines(h.Inlines, link);
                    h.RequestNavigate += (s, e) => { OpenInBrowser(e.Uri); e.Handled = true; };
                    target.Add(h);
                    break;
                case LineBreakInline:
                    target.Add(new LineBreak());
                    break;
                default:
                    if (inline is ContainerInline nested) { AppendInlines(target, nested); }
                    break; // never add inline.ToString()
            }
        }
    }

    // Natural width is measured from the source markdown lines (reliable at any constraint).
    private static double ComputeNaturalWidth(string markdown)
    {
        var prose = new Typeface("Segoe UI");
        var code  = new Typeface("Consolas");
        double max = 0; bool inFence = false;
        foreach (string line in markdown.Replace("\r\n", "\n").Split('\n'))
        {
            string t = line.TrimStart();
            if (t.StartsWith("```")) { inFence = !inFence; continue; }
            if (line.Length == 0) { continue; }

            double size = 14; Typeface tf = prose;
            if (inFence) { tf = code; }
            else if (t.StartsWith("#")) { size = 20; } // heading rendered larger -> measure larger

            var ft = new FormattedText(line, CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight, tf, size, Brushes.Black, 1.0);
            max = Math.Max(max, ft.WidthIncludingTrailingWhitespace);
        }
        return max + 12; // padding / caret / bold-and-inline-formatting buffer
    }

    // Read-only RichTextBox swallows MouseWheel; re-raise a bubbling MouseWheel on the parent.
    private static void ForwardWheelToParent(object sender, MouseWheelEventArgs e)
    {
        if (e.Handled) { return; }
        e.Handled = true;
        var args = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta)
        {
            RoutedEvent = UIElement.MouseWheelEvent,
            Source = sender
        };
        if (sender is RichTextBox host && host.Parent is UIElement parent) { parent.RaiseEvent(args); }
    }

    // Reject non-absolute URLs. Minimal helper.
    private static Uri? SafeUri(string? url)
        => Uri.TryCreate(url, UriKind.Absolute, out Uri? uri) ? uri : null;

    // Untrusted model output: allow http/https only before shell-executing a link.
    private static void OpenInBrowser(Uri? uri)
    {
        if (uri is null) { return; }
        if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) { return; } // allow-list
        try { Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true }); }
        catch { /* a navigation failure must not crash the chat */ }
    }

    // A content-hugging read-only RichTextBox: a read-only RichTextBox cannot self-measure its
    // natural width (it collapses to ~0 at an infinite constraint and is greedy at a finite one),
    // so the natural width is computed externally (ComputeNaturalWidth) and forced here.
    private sealed class HuggingRichTextBox : RichTextBox
    {
        public double NaturalWidth { get; set; }

        protected override Size MeasureOverride(Size constraint)
        {
            double width = double.IsInfinity(constraint.Width)
                ? NaturalWidth
                : Math.Min(NaturalWidth, constraint.Width); // hug short / wrap long
            Size measured = base.MeasureOverride(new Size(width, constraint.Height));
            return new Size(width, measured.Height);
        }
    }
}

Optional: real table mapping

UseAdvancedExtensions() parses pipe tables, but an unhandled Table falls through to the generic container fallback and renders as flat cell text. To promote it to a grid, add an arm to RenderBlock:

case Markdig.Extensions.Tables.Table mdTable:
    return BuildTable(mdTable); // Markdig TableRow/TableCell -> System.Windows.Documents.Table/TableRow/TableCell
// BuildTable creates a WPF Table with one TableRowGroup; each TableCell hosts Paragraph(s) via AppendInlines.

XAML Usage

<Window xmlns:controls="clr-namespace:{Namespace}.Controls">
    <!-- Markdown is a string the ViewModel appends to as tokens stream in. -->
    <controls:$0 Markdown="{Binding CurrentMarkdown}" />
</Window>

File Location

{Project}/
└── Controls/
    └── $0.cs

Notes

  • Theme foreground: a FlowDocument/TextBlock built in code does not inherit a theme foreground (renders black on a dark theme). The single SetResourceReference(Control.ForegroundProperty, ...) on the host fixes it; children inherit it.
  • Invalid theme keys throw at runtime, not build. Referencing a non-existent {ui:ThemeResource ...}/resource key compiles and then throws XamlParseException on first render. Only use keys verified to exist in the kit.
  • SafeUri, BuildThematicBreak are minimal helpers — adjust to taste.

Related

  • Knowledge (fetch via WpfDevPackMcp get_wpf_topic): rendering-markdown-in-wpf, displaying-selectable-rich-text-in-wpf, integrating-wpfui-fluent, authoring-wpf-controls.
  • Sibling scaffolders: this presenter is one of the pieces emitted by /wpf-dev-pack:make-wpf-chatclient (the one-button full chat client). Pair it with /wpf-dev-pack:make-wpf-chat-bubble-template to place it inside role-differentiated bubbles.

WPF Project Scaffolder

If $0 is empty, use the AskUserQuestion tool to ask: "Enter the WPF project name (e.g., MyApp, Dashboard)". Do NOT proceed until a valid name is provided. Use the response as the ProjectName for all subsequent steps.

Scaffold a WPF project named $0 with MVVM, DI, and best practices.

Usage

# Default project (recommended) - CommunityToolkit.Mvvm + GenericHost
/wpf-dev-pack:make-wpf-project $0

# Minimal structure
/wpf-dev-pack:make-wpf-project $0 --minimal

# Full structure (all layers separated)
/wpf-dev-pack:make-wpf-project $0 --full

# Prism framework (module-based architecture)
/wpf-dev-pack:make-wpf-project $0 --prism

Framework Options

OptionFrameworkFeatures
(default)CommunityToolkit.MvvmLightweight, Source Generator, GenericHost DI
--prismPrism.DryIocRegion Navigation, Module, Dialog Service

Prism details: See PRISM.md for complete Prism project structure and examples.

Project naming (consistency contract): the WPF application project is suffixed .WpfApp. The make-wpf-viewmodel and make-wpf-service generators locate the app project by this suffix to place Views and register DI. Keep .WpfApp so the whole make-wpf-* family wires into one solution.


Project Structures

Default Structure

$0/
├── $0.sln
├── $0.WpfApp/                  # WPF Application (entry point + Views)
│   ├── App.xaml                # merges Mappings.xaml
│   ├── App.xaml.cs             # GenericHost + DI
│   ├── MainWindow.xaml         # shell: ContentControl nav host
│   ├── MainWindow.xaml.cs
│   ├── GlobalUsings.cs
│   ├── Mappings.xaml           # ViewModel→View DataTemplate map
│   ├── Views/
│   ├── Converters/
│   └── $0.WpfApp.csproj
├── $0.ViewModels/             # ViewModel (pure C#, no System.Windows)
│   ├── MainViewModel.cs
│   ├── GlobalUsings.cs
│   └── $0.ViewModels.csproj
└── $0.Core/                   # Business logic + service interfaces
    ├── Models/
    ├── Services/
    └── $0.Core.csproj

Minimal Structure

$0/
├── $0.sln
└── $0/
    ├── App.xaml
    ├── App.xaml.cs
    ├── MainWindow.xaml
    ├── MainWindow.xaml.cs
    ├── Mappings.xaml
    ├── ViewModels/
    │   └── MainViewModel.cs
    ├── Views/
    ├── Models/
    ├── Services/
    └── $0.csproj

Full Structure

$0/
├── $0.slnx
├── src/
│   ├── $0.Abstractions/       # Interfaces, abstract classes
│   ├── $0.Core/               # Business logic
│   ├── $0.ViewModels/         # ViewModel
│   ├── $0.WpfServices/        # WPF services (CollectionView etc.)
│   ├── $0.UI/                 # CustomControl library (Themes/Generic.xaml)
│   └── $0.WpfApp/             # WPF Application
└── tests/
    ├── $0.Core.Tests/
    └── $0.ViewModels.Tests/

Prism Structure (--prism)

See PRISM.md for complete structure.


Composition Style (CommunityToolkit.Mvvm)

This scaffold establishes ViewModel First Composition + Stateful ViewModel from the start:

  • the shell MainViewModel exposes CurrentViewModel,
  • the shell MainWindow hosts it in a ContentControl, and
  • Mappings.xaml resolves the View from the ViewModel type via an implicit DataTemplate (no x:Key).

Add screens with /wpf-dev-pack:make-wpf-viewmodel <Name> --with-view, which appends one DataTemplate to Mappings.xaml and registers DI. ViewModelLocator, code-behind DataContext = new VM(), and inline XAML DataContext are prohibited (see prohibitions.md).


Generated Files

$0.WpfApp.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net10.0-windows</TargetFramework>
    <!-- Assembly is $0.WpfApp but root namespace is $0, so View/ViewModel
         namespaces ($0.Views / $0.ViewModels) line up across projects. -->
    <RootNamespace>$0</RootNamespace>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.*" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.*" />
  </ItemGroup>

  <ItemGroup>
    <!-- Forward slashes: MSBuild accepts them on Windows, and a "\$" sequence
         in this skill body is consumed as an argument escape at invocation. -->
    <ProjectReference Include="../$0.ViewModels/$0.ViewModels.csproj" />
    <ProjectReference Include="../$0.Core/$0.Core.csproj" />
  </ItemGroup>

</Project>

App.xaml (merges Mappings.xaml)

<Application x:Class="$0.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Mappings.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

No StartupUri — the host resolves and shows MainWindow from DI in OnStartup.

App.xaml.cs (with DI)

namespace $0;

public partial class App : Application
{
    private readonly IHost _host;

    public App()
    {
        _host = Host.CreateDefaultBuilder()
            .ConfigureServices((context, services) =>
            {
                // Services — add with /wpf-dev-pack:make-wpf-service
                // (that generator adds the registration + the GlobalUsings entry)

                // ViewModels
                services.AddSingleton<MainViewModel>();

                // Windows
                services.AddSingleton<MainWindow>();
            })
            .Build();
    }

    protected override async void OnStartup(StartupEventArgs e)
    {
        await _host.StartAsync();

        var mainWindow = _host.Services.GetRequiredService<MainWindow>();
        mainWindow.DataContext = _host.Services.GetRequiredService<MainViewModel>();
        mainWindow.Show();

        base.OnStartup(e);
    }

    protected override async void OnExit(ExitEventArgs e)
    {
        await _host.StopAsync();
        _host.Dispose();
        base.OnExit(e);
    }
}

MainWindow.xaml (shell — ContentControl nav host)

<Window x:Class="$0.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="{Binding Title}" Height="600" Width="800">
    <!-- CurrentViewModel is resolved to its View by Mappings.xaml (ViewModel First). -->
    <ContentControl Content="{Binding CurrentViewModel}" />
</Window>
namespace $0;

public partial class MainWindow : Window
{
    public MainWindow() => InitializeComponent();
}

Mappings.xaml (ViewModel → View)

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:vm="clr-namespace:$0.ViewModels;assembly=$0.ViewModels"
                    xmlns:views="clr-namespace:$0.Views">

    <!-- /wpf-dev-pack:make-wpf-viewmodel appends one entry per screen, e.g.:
    <DataTemplate DataType="{x:Type vm:HomeViewModel}">
        <views:HomeView />
    </DataTemplate>
    -->

</ResourceDictionary>

MainViewModel.cs (shell)

namespace $0.ViewModels;

public sealed partial class MainViewModel : ObservableObject
{
    [ObservableProperty] private string _title = "$0";

    // ViewModel First: assign a screen ViewModel to CurrentViewModel and
    // Mappings.xaml resolves the matching View into the shell ContentControl.
    // Set this once you add a screen with /wpf-dev-pack:make-wpf-viewmodel.
    [ObservableProperty] private object? _currentViewModel;
}

GlobalUsings.cs (WpfApp)

global using System;
global using System.Collections.Generic;
global using System.Collections.ObjectModel;
global using System.Linq;
global using System.Threading.Tasks;
global using System.Windows;
global using CommunityToolkit.Mvvm.ComponentModel;
global using CommunityToolkit.Mvvm.Input;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using $0.ViewModels;

When other generators need more global usings (e.g. make-wpf-converter needs System.Windows.Data / System.Windows.Markup), append to this existing GlobalUsings.cs — do not create a second GlobalUsings.cs in the same project (duplicate global using directives fail to compile).


CLI Commands

# Create solution
dotnet new sln -n $0

# Create projects (note the .WpfApp suffix on the application project)
dotnet new wpf -n $0.WpfApp
dotnet new classlib -n $0.ViewModels
dotnet new classlib -n $0.Core

# Add projects to solution
dotnet sln add $0.WpfApp/$0.WpfApp.csproj
dotnet sln add $0.ViewModels/$0.ViewModels.csproj
dotnet sln add $0.Core/$0.Core.csproj

# Add project references
dotnet add $0.WpfApp reference $0.ViewModels
dotnet add $0.WpfApp reference $0.Core
dotnet add $0.ViewModels reference $0.Core

# Add packages
dotnet add $0.WpfApp package CommunityToolkit.Mvvm
dotnet add $0.WpfApp package Microsoft.Extensions.Hosting
dotnet add $0.ViewModels package CommunityToolkit.Mvvm

Prism vs CommunityToolkit.Mvvm

FeatureCommunityToolkit.MvvmPrism
Base ClassObservableObjectBindableBase
CommandRelayCommand (Source Gen)DelegateCommand
DI ContainerGenericHost (any)DryIoc, Unity, etc.
NavigationCurrentViewModel + Mappings.xamlIRegionManager
DialogManual implementationIDialogService
ModuleNot supportedIModule
Best forSmall-Medium appsMedium-Large apps

Next Steps

  1. Add a screen (View + ViewModel): /wpf-dev-pack:make-wpf-viewmodel <Name> --with-view
  2. Add a CustomControl: /wpf-dev-pack:make-wpf-custom-control <Name>
  3. Add a Converter: /wpf-dev-pack:make-wpf-converter <Name>
  4. Add a Service: /wpf-dev-pack:make-wpf-service <Name>

Related knowledge topics (via WpfDevPackMcp)

Fetch with WpfDevPackMcp get_wpf_topic:

  • structuring-wpf-projects — project / solution structure
  • configuring-dependency-injection — DI setup
  • implementing-communitytoolkit-mvvm — MVVM pattern

WPF Service Generator

If $0 is empty, use the AskUserQuestion tool to ask: "Enter the Service name (e.g., DataExport, FileManager)". Do NOT proceed until a valid name is provided. Use the response as the ServiceName for all subsequent steps.

Generate a $0Service with interface + implementation class + DI registration. Automatically places files in the correct project based on solution structure. If --no-interface is appended, skip interface generation.

  • Replace {Namespace} with the project's root namespace detected from csproj or existing code.

Usage

# Interface + Implementation + DI registration
/wpf-dev-pack:make-wpf-service DataExport

# Implementation only (no interface) — for simple services
/wpf-dev-pack:make-wpf-service FileManager --no-interface

Execution Procedure

Step 1: Parse $0

  • $0 is the service name (without Service suffix — auto-appended)
    • e.g., DataExport → IDataExportService.cs + DataExportService.cs
  • --no-interface flag: Skip interface generation (class-only)

Step 2: Locate Target Projects

Search for solution file and identify projects by naming convention:

Project SuffixPurposeFiles Placed
.AbstractionsInterfacesI$0Service.cs
.CoreBusiness logic$0Service.cs (UI-independent)
.WpfServicesWPF-dependent services$0Service.cs (if needs WPF types)
.WpfAppApplicationDI registration in App.xaml.cs

Fallback rules (keep the interface visible to both the implementation and the app):

  • No .Abstractions project → place the interface in .Core (beside the implementation). Do NOT put it in the WPF app project: .Core cannot reference the app, so an interface placed there is unreachable from the implementation in .Core.
  • No .Core or .WpfServices (no separate logic project) → place both interface and implementation in the app's Services/ folder.
  • Single project solution → both files in Services/ folder.

Step 3: Generate Interface (unless --no-interface)

Create I$0Service.cs:

namespace {Namespace}.Services;

public interface I$0Service
{
    // TODO: Define service contract
    // TODO: 서비스 계약 정의
}

Step 4: Generate Implementation

Create $0Service.cs:

namespace {Namespace}.Services;

public sealed class $0Service : I$0Service
{
    // TODO: Implement service
    // TODO: 서비스 구현
}

If --no-interface:

namespace {Namespace}.Services;

public sealed class $0Service
{
    // TODO: Implement service
    // TODO: 서비스 구현
}

Step 5: Register in DI Container

CommunityToolkit.Mvvm (GenericHost)

Locate App.xaml.cs and add in ConfigureServices:

// With interface
services.AddSingleton<I$0Service, $0Service>();

// Without interface (--no-interface)
services.AddSingleton<$0Service>();
Prism 9

Locate App.xaml.cs and add in RegisterTypes:

// With interface
containerRegistry.RegisterSingleton<I$0Service, $0Service>();

// Without interface (--no-interface)
containerRegistry.RegisterSingleton<$0Service>();

GlobalUsings: make sure App.xaml.cs can resolve the service type — add global using {Namespace}.Services; to the app's existing GlobalUsings.cs if absent (the Services namespace now exists, so the using resolves). Do not create a second GlobalUsings.cs.

Step 6: Report Results

Output list of generated/modified files and next steps guidance.


Generated File Structure

With Interface (default)

{AbstractionsProject}/
└── Services/
    └── I$0Service.cs

{CoreProject}/
└── Services/
    └── $0Service.cs

{WpfAppProject}/
└── App.xaml.cs              (DI registration added)

Without Interface (--no-interface)

{CoreProject}/
└── Services/
    └── $0Service.cs

{WpfAppProject}/
└── App.xaml.cs              (DI registration added)

If there is no .Abstractions project (the default 3-project structure), place I$0Service.cs in $0.Core/Services/ alongside $0Service.cs — never in the WPF app project, which .Core cannot reference.


Error Handling

  • Missing service name → output usage instructions
  • No WPF project found → suggest /wpf-dev-pack:make-wpf-project first
  • Duplicate service → warn and abort
  • Multiple candidate projects → ask user which to use

WPF UserControl Generator

If $0 is empty, use the AskUserQuestion tool to ask: "Enter the UserControl name (e.g., SearchBox, UserProfile)". Do NOT proceed until a valid name is provided. Use the response as the ControlName for all subsequent steps.

Generate a $0Control UserControl with XAML and code-behind. If --with-viewmodel is appended, also generate a corresponding ViewModel.

  • Replace {Namespace} with the project's root namespace detected from csproj or existing code.
  • Replace {Project} with the target project path.

Usage

# Basic UserControl
/wpf-dev-pack:make-wpf-usercontrol SearchBox

# With ViewModel
/wpf-dev-pack:make-wpf-usercontrol UserProfile --with-viewmodel

Generated Files

$0Control.xaml

<UserControl x:Class="{Namespace}.Controls.$0Control"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             d:DesignHeight="100" d:DesignWidth="300">

    <Grid>
        <!-- TODO: Add your UI elements here -->
    </Grid>

</UserControl>

$0Control.xaml.cs

namespace {Namespace}.Controls;

/// <summary>
/// $0 UserControl.
/// </summary>
public partial class $0Control : UserControl
{
    #region Dependency Properties

    public static readonly DependencyProperty HeaderProperty =
        DependencyProperty.Register(
            nameof(Header),
            typeof(string),
            typeof($0Control),
            new PropertyMetadata(string.Empty));

    /// <summary>
    /// Gets or sets the header text.
    /// </summary>
    public string Header
    {
        get => (string)GetValue(HeaderProperty);
        set => SetValue(HeaderProperty, value);
    }

    #endregion

    public $0Control()
    {
        InitializeComponent();
    }
}

With ViewModel Option

$0ControlViewModel.cs

namespace {Namespace}.ViewModels;

public partial class $0ControlViewModel : ObservableObject
{
    [ObservableProperty] private string _title = string.Empty;

    [RelayCommand]
    private void Submit()
    {
        // TODO: Implement submit logic
    }
}

$0Control.xaml (with ViewModel)

No inline runtime DataContext. Inline <UserControl.DataContext> (and code-behind DataContext = new …) is prohibited (P-001-c). Declare a design-time d:DataContext for IntelliSense only; the runtime DataContext is supplied by the composition root — the parent passes the VM, or a Mappings.xaml DataTemplate resolves this control as the View for $0ControlViewModel (ViewModel First). This matches make-wpf-viewmodel.

<UserControl x:Class="{Namespace}.Controls.$0Control"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:vm="clr-namespace:{Namespace}.ViewModels"
             mc:Ignorable="d"
             d:DataContext="{d:DesignInstance Type=vm:$0ControlViewModel}">

    <Grid>
        <TextBlock Text="{Binding Title}"/>
    </Grid>

</UserControl>

UserControl vs CustomControl

AspectUserControlCustomControl
PurposeReuse within specific appLibrary distribution
StylingLimitedFull ControlTemplate replacement
ComplexityLowHigh
CreationXAML + Code-behindClass + Generic.xaml

When to Use UserControl

  • ✅ UI composition used only within the app
  • ✅ Rapid prototyping
  • ✅ Simple composite controls
  • ❌ External library distribution → Use CustomControl

File Location

{Project}/
├── Controls/
│   ├── $0Control.xaml
│   └── $0Control.xaml.cs
└── ViewModels/
    └── $0ControlViewModel.cs  (with --with-viewmodel option)

DependencyProperty Pattern

Use DependencyProperty to receive external bindings in UserControl:

public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register(
        nameof(Value),
        typeof(string),
        typeof($0Control),
        new FrameworkPropertyMetadata(
            string.Empty,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            OnValueChanged));

public string Value
{
    get => (string)GetValue(ValueProperty);
    set => SetValue(ValueProperty, value);
}

private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is $0Control control)
    {
        // Handle value change
    }
}
<!-- Usage example -->
<local:$0Control Value="{Binding MyValue, Mode=TwoWay}"/>

WPF ViewModel Generator

If $0 is empty, use the AskUserQuestion tool to ask: "Enter the ViewModel name (e.g., Dashboard, Settings)". Do NOT proceed until a valid name is provided. Use the response as the ViewModelName for all subsequent steps.

Generate a $0ViewModel class with optional View, DI registration, and DataTemplate mapping. Follows the wpf-dev-pack composition style: ViewModel First Composition + Stateful ViewModel when using CommunityToolkit.Mvvm (Mappings.xaml + implicit DataTemplate resolves the View from the ViewModel type), or View First Composition + Stateful ViewModel when using Prism 9 (RegisterForNavigation + IRegionManager). ViewModelLocator, code-behind DataContext = new VM(), and inline XAML DataContext are prohibited (see prohibitions.md and docs/TERMINOLOGY.md).

  • Replace {Namespace} with the project's root namespace detected from csproj or existing code.
  • Replace {ViewModelNamespace} with the ViewModel project's CLR namespace for XAML xmlns declaration.

Usage

# ViewModel + View + DI + DataTemplate mapping (full)
/wpf-dev-pack:make-wpf-viewmodel Dashboard --with-view

# ViewModel + DI only (no View, no mapping)
/wpf-dev-pack:make-wpf-viewmodel Settings

# ViewModel + View without DataTemplate mapping
/wpf-dev-pack:make-wpf-viewmodel Report --with-view --no-mapping

Execution Procedure

Step 1: Parse $0

  • $0 is the ViewModel name (without ViewModel suffix — auto-appended)
    • e.g., Dashboard → DashboardViewModel.cs + DashboardView.xaml
  • --with-view flag: Generate View XAML + code-behind
  • --no-mapping flag: Skip DataTemplate mapping registration

Step 2: Locate Target Projects

Search for solution file and identify projects by naming convention:

Project SuffixPurposeFiles Placed
.ViewModelsViewModel project$0ViewModel.cs
.WpfAppWPF ApplicationViews/$0View.xaml, DI registration
.WpfServicesWPF Services(referenced for DI)

Fallback: If no .ViewModels project exists, place ViewModel in ViewModels/ folder of main WPF project.

Step 3: Generate ViewModel

Create $0ViewModel.cs:

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace {Namespace}.ViewModels;

public sealed partial class $0ViewModel : ObservableObject
{
    [ObservableProperty] private string _title = "$0";

    [RelayCommand]
    private void Loaded()
    {
        // TODO: Initialize data
        // TODO: 데이터 초기화
    }
}

Step 4: Generate View (if --with-view)

Create Views/$0View.xaml:

<UserControl x:Class="{Namespace}.Views.$0View"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:vm="{ViewModelNamespace}"
             mc:Ignorable="d"
             d:DataContext="{d:DesignInstance vm:$0ViewModel}"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <TextBlock Text="{Binding Title}"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   FontSize="24" />
    </Grid>
</UserControl>

Create Views/$0View.xaml.cs:

namespace {Namespace}.Views;

public partial class $0View
{
    public $0View()
    {
        InitializeComponent();
    }
}

Step 5: Register in DI Container

Locate App.xaml.cs and add registration inside ConfigureServices:

// In ConfigureServices method
services.AddSingleton<$0ViewModel>();

With --with-view, register only the ViewModel — the View is instantiated by the Mappings.xaml DataTemplate (ViewModel First), so it is NOT registered in DI (registering it would also force a $0.Views using in App.xaml.cs):

services.AddSingleton<$0ViewModel>();

Step 6: Add DataTemplate Mapping (unless --no-mapping)

Locate Mappings.xaml (or ViewModelMappings.xaml) and add:

<DataTemplate DataType="{x:Type vm:$0ViewModel}">
    <views:$0View />
</DataTemplate>

If Mappings.xaml does not exist, create it and merge into App.xaml:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Mappings.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Step 7: Report Results

Output list of generated/modified files and next steps guidance.


Generated File Structure

{ViewModelsProject}/
└── $0ViewModel.cs

{WpfAppProject}/
├── Views/
│   ├── $0View.xaml           (if --with-view)
│   └── $0View.xaml.cs        (if --with-view)
├── Mappings.xaml                  (modified or created)
└── App.xaml.cs                    (DI registration added)

Error Handling

  • Missing ViewModel name → output usage instructions
  • No WPF project found → suggest /wpf-dev-pack:make-wpf-project first
  • Duplicate ViewModel → warn and abort
  • Missing Mappings.xaml → create with App.xaml merge

Prism 9 사용자: See PRISM.md for Prism-specific generation patterns.

Set WpfDevPackMcp Branch

Sets the branch field in ~/.wpf-dev-pack-mcp/config.json — the branch the MCP server fetches/serves WPF knowledge from — leaving repoPath unchanged.

If $0 is empty, use AskUserQuestion to ask which branch to track (e.g., main). Do NOT proceed until a branch is provided.

dotnet "${CLAUDE_PLUGIN_ROOT}/scripts/SetWpfDevPackBranch.cs" "$0"

Surface the output verbatim, including any ! warning (e.g. repoPath not set yet → run /wpf-dev-pack:set-repo-path first). The new branch takes effect on the next WpfDevPackMcp refresh.

When Managed=true (see /wpf-dev-pack:set-repo-managed), refresh hard-resets the clone to origin/<branch>, so the branch must exist on the remote. View the current branch with /wpf-dev-pack:show-wpf-dev-pack-config.

Set WpfDevPackMcp Managed Flag

Sets Managed in ~/.wpf-dev-pack-mcp/state.json (preserving LastPullUtc). This flag decides how the server refreshes the clone at repoPath.

If $0 is empty, use AskUserQuestion to ask for true or false. Do NOT proceed until a value is provided.

dotnet "${CLAUDE_PLUGIN_ROOT}/scripts/SetWpfDevPackManaged.cs" "$0"

What it controls (mcp/Git/RepoRefresher.cs):

  • true — on refresh the server runs git fetch + git reset --hard origin/<branch> on repoPath. Use ONLY for a dedicated clone the server created/owns. Never set true when repoPath is your active working repo — a refresh will discard uncommitted changes and reset the branch to origin/<branch>, destroying local work.
  • false — refresh is non-destructive: git pull --ff-only when the tree is clean, skip when dirty. Use when repoPath points at your own working clone.

Surface the output verbatim. Inspect the current flag with /wpf-dev-pack:show-wpf-dev-pack-config.

Set WpfDevPackMcp Repository Path

Records the on-disk location of a local clone of christian289/dotnet-with-claudecode so the WpfDevPackMcp MCP server can serve WPF knowledge topics from knowledge/ (at the repo root).

If $0 is empty, use AskUserQuestion to ask for the absolute path to the local clone (e.g., C:/Users/<you>/src/dotnet-with-claudecode). Do NOT proceed until a path is provided. Optionally accept a branch as $1 (default main).

Run the file-based app to validate and persist the path:

dotnet "${CLAUDE_PLUGIN_ROOT}/scripts/SetWpfDevPackRepoPath.cs" "$0" "$1"

Surface the app's output verbatim, including any ! warnings (path missing, no .git, etc.). After it succeeds, tell the user the WpfDevPackMcp tools are now usable and that the server will clone/pull the repo as needed.

Companion skills

  • /wpf-dev-pack:show-wpf-dev-pack-config — view the current config.json / state.json paths and values (and any WPFDEVPACK_REPO_PATH env override).
  • /wpf-dev-pack:set-repo-branch <branch> — change the tracked branch (preserves repoPath).
  • /wpf-dev-pack:set-repo-managed <true|false> — control whether refresh hard-resets the clone. Set false if you ever point repoPath at your own working repo, so a refresh cannot git reset --hard your working tree.

Show WpfDevPackMcp Configuration

Print the on-disk WpfDevPackMcp configuration and server state so the user can see exactly what the MCP server reads and from where.

Run the file-based app and surface its output verbatim:

dotnet "${CLAUDE_PLUGIN_ROOT}/scripts/ShowWpfDevPackConfig.cs"

It prints the absolute paths and current contents of:

  • ~/.wpf-dev-pack-mcp/config.json — user-written repoPath + branch
  • ~/.wpf-dev-pack-mcp/state.json — server-managed LastPullUtc + Managed

plus the WPFDEVPACK_REPO_PATH and WPFDEVPACK_PULL_TTL_MINUTES environment overrides. When WPFDEVPACK_REPO_PATH is set it overrides config.json's repoPath — a common cause of "the MCP isn't reading the repo I configured."

To change values: /wpf-dev-pack:set-repo-path (repoPath), /wpf-dev-pack:set-repo-branch (branch), /wpf-dev-pack:set-repo-managed (Managed flag).

Converter Patterns

Standards for implementing IValueConverter in wpf-dev-pack projects.


MarkupExtension Singleton Pattern

Every converter is a MarkupExtension so it can be used directly in XAML without declaring a resource, and ProvideValue returns a single shared instance (converters are stateless, so a shared instance is safe and avoids ResourceDictionary clutter). This is the canonical converter pattern, matching the /wpf-dev-pack:make-wpf-converter scaffolder and the using-converter-markup-extension knowledge topic. Pick this one pattern — do NOT also expose a separate static Instance property.

Derive from a small base class (the scaffolder generates it once per project):

namespace MyApp.Converters;

public abstract class ConverterMarkupExtension<T> : MarkupExtension, IValueConverter
    where T : class, new()
{
    private static readonly Lazy<T> _converter = new(() => new T());

    public override object ProvideValue(IServiceProvider serviceProvider) => _converter.Value;

    public abstract object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture);

    public virtual object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
        => throw new NotSupportedException("ConvertBack is not supported.");
}

public sealed class BoolToVisibilityConverter : ConverterMarkupExtension<BoolToVisibilityConverter>
{
    public override object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is null || value == DependencyProperty.UnsetValue)
            return Visibility.Collapsed;

        var invert = parameter is "Invert" or "invert";
        return (value is bool b && (b ^ invert)) ? Visibility.Visible : Visibility.Collapsed;
    }
}

Usage in XAML (no ResourceDictionary entry required):

<TextBlock Visibility="{Binding IsActive,
               Converter={converters:BoolToVisibilityConverter}}" />

Pure Function Requirement

Converters must be pure functions:

  • No side effects (no writes to fields, services, or ViewModels)
  • No dependency on external state (no static mutable state, no DateTime.Now inside Convert)
  • Same inputs always produce the same output

If conversion logic requires external context, pass it via the ConverterParameter or via a MultiBinding with IMultiValueConverter.


null and UnsetValue Handling

Always handle both null and DependencyProperty.UnsetValue as the first check in Convert:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value is null || value == DependencyProperty.UnsetValue)
        return DependencyProperty.UnsetValue;   // or a safe default

    // normal conversion logic
}

Returning DependencyProperty.UnsetValue from Convert signals WPF to use the property's default value rather than throwing a binding error.


TemplateBinding vs Binding in ControlTemplate

Inside a ControlTemplate, use TemplateBinding (not Binding) to reference the templated parent's properties. TemplateBinding is a lightweight one-way binding that avoids the overhead of a full Binding object.

<!-- Correct: TemplateBinding for ControlTemplate property references -->
<ControlTemplate TargetType="{x:Type local:MyButton}">
    <Border Background="{TemplateBinding Background}"
            BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness}"
            CornerRadius="4">
        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
    </Border>
</ControlTemplate>
<!-- Incorrect: Binding with RelativeSource is verbose and slower -->
<Border Background="{Binding Background,
            RelativeSource={RelativeSource TemplatedParent}}">

Use Binding with RelativeSource=TemplatedParent only when you need two-way binding or a converter applied to a templated-parent property — TemplateBinding is one-way only and does not support converters directly.

Freezable Performance

Rules for using Freeze() on WPF Freezable objects to maximize rendering performance.


Rule: Freeze All Freezable Objects

Call Freeze() on every Freezable after it is fully configured and before it is used for rendering.

Applies to: Brush, Pen, Geometry, Transform, PathGeometry, GradientBrush, ImageBrush, DrawingGroup, and all other Freezable subclasses.


Why Freeze Matters

Without FreezeWith Freeze
Object tracked for change notificationsNo change tracking overhead
Cannot be shared across threadsSharable across all threads
WPF retains full change-event infrastructureInfrastructure freed immediately
Higher memory footprintMinimal memory footprint

Frozen objects are immutable. WPF can cache and reuse them across render passes without defensive copies.


Correct vs Incorrect

// Incorrect: brush created but never frozen
protected override void OnRender(DrawingContext dc)
{
    var brush = new SolidColorBrush(Colors.CornflowerBlue);
    var pen   = new Pen(brush, 2.0);
    dc.DrawRectangle(brush, pen, new Rect(0, 0, 100, 50));
}

// Correct: freeze immediately after configuration
protected override void OnRender(DrawingContext dc)
{
    var brush = new SolidColorBrush(Colors.CornflowerBlue);
    brush.Freeze();

    var pen = new Pen(brush, 2.0);
    pen.Freeze();

    dc.DrawRectangle(brush, pen, new Rect(0, 0, 100, 50));
}

OnRender Pattern: Create in Constructor, Reuse in OnRender

Creating Freezable objects inside OnRender allocates on every paint cycle. Create them once in the constructor (or a lazy initializer), freeze them, then reuse the frozen instances in every OnRender call.

public class MyVisual : FrameworkElement
{
    private readonly SolidColorBrush _fillBrush;
    private readonly Pen             _borderPen;

    public MyVisual()
    {
        _fillBrush = new SolidColorBrush(Colors.CornflowerBlue);
        _fillBrush.Freeze();

        _borderPen = new Pen(Brushes.DarkBlue, 1.5);
        _borderPen.Freeze();
    }

    protected override void OnRender(DrawingContext dc)
    {
        // No allocation here — reuse frozen instances
        dc.DrawRectangle(_fillBrush, _borderPen, new Rect(0, 0, ActualWidth, ActualHeight));
    }
}

If a property changes and a new brush is needed, create and freeze the replacement, then call InvalidateVisual() once.

MVVM Constraints

Rules for enforcing strict MVVM layer separation in wpf-dev-pack projects.


Prohibited DLL References in ViewModel Projects

ViewModel projects must NOT reference these assemblies:

  • WindowsBase.dll
  • PresentationFramework.dll
  • PresentationCore.dll

If any of these appear in a .csproj targeting the ViewModel layer, remove them immediately.


Prohibited Using Statements

The following namespaces must never appear in ViewModel code:

// Prohibited in ViewModel projects
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Input;   // except ICommand — use CommunityToolkit.Mvvm instead

Allowed Using Statements

These namespaces are safe for ViewModels:

// Allowed
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.ComponentModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

ViewModel Type Restrictions

ViewModel properties and constructor parameters must use BCL types only:

  • string, int, double, bool, decimal, DateTime, Guid
  • ObservableCollection<T>, List<T>, IEnumerable<T>
  • Other ViewModels or domain model types

Do NOT expose WPF types (Brush, Visibility, ImageSource, Thickness, etc.) as ViewModel properties. Convert in the View layer using converters or triggers.


CommunityToolkit.Mvvm

Prefer CommunityToolkit.Mvvm for all ViewModel base classes and commands:

  • Inherit from ObservableObject or ObservableRecipient
  • Use [ObservableProperty] for bindable properties (source-generated)
  • Use [RelayCommand] for commands (source-generated)
  • Never hand-roll INotifyPropertyChanged or ICommand implementations

Prohibitions

Items explicitly banned from wpf-dev-pack. Do NOT introduce any of these during code generation, review, or refactoring.

For terminology used below (View First / ViewModel First Composition, Stateful / Stateless ViewModel), see docs/TERMINOLOGY.md.

Adopted combinations (per chosen MVVM framework):

  • CommunityToolkit.Mvvm path — ViewModel First Composition + Stateful ViewModel (Mappings.xaml + implicit DataTemplate)
  • Prism 9 path — View First Composition + Stateful ViewModel (RegisterForNavigation + IRegionManager.RequestNavigate)

P-001: Mixing alternate composition mechanisms in the same project

P-001-a: Prism ViewModelLocator.AutoWireViewModel is prohibited

Prohibited:

<Window prism:ViewModelLocator.AutoWireViewModel="True" />

Classification: View First Composition (an alternate mechanism inside Prism)

Reason: The Prism path's single matching mechanism is RegisterForNavigation + IRegionManager.RequestNavigate. ViewModelLocator locates and attaches the ViewModel by naming convention after the View is instantiated; using both mechanisms in the same Prism project produces two parallel matching paths, increasing maintenance and cognitive cost.

P-001-b: DataContext = new XxxViewModel() in View code-behind is prohibited

Prohibited:

public XxxView()
{
    InitializeComponent();
    DataContext = new XxxViewModel();   // Prohibited
}

Classification: View First Composition (imperative variant)

Reason: In the CommunityToolkit.Mvvm path the single matching mechanism is Mappings.xaml + implicit DataTemplate (ViewModel First). A View directly choosing its own VM breaks that single-path policy. In the Prism path the single mechanism is RegisterForNavigation; manual DataContext assignment likewise breaks single-path.

P-001-c: Inline XAML DataContext declaration is prohibited

Prohibited:

<UserControl.DataContext>
    <vm:XxxViewModel />   <!-- Prohibited -->
</UserControl.DataContext>

Classification: View First Composition (declarative variant)

Reason: Same as P-001-b. Declarative specification of the VM type by the View is still the View choosing its own VM.

P-001-d: Introducing any other matching mechanism is prohibited

Prohibited: Adding any View-VM matching mechanism beyond the one selected for the chosen framework (e.g., naming-convention auto-matching, custom locators, reflection-based wiring).

Reason: Guarantees a single matching path per project. Co-existence of multiple mechanisms increases maintenance cost and cognitive load.


P-002: System.Windows.* UI types in ViewModel classes (except ICommand)

Prohibited: References to System.Windows.* UI types (Visibility, Brush, ImageSource, Thickness, Window, etc.) from inside ViewModel classes.

Allowed exception: System.Windows.Input.ICommand (used by both RelayCommand and DelegateCommand).

Reason: Guarantees ViewModel testability and isolates the WPF framework dependency. Complies with the "view model is unaware of the view" principle from Microsoft's MVVM guidance. UI-type conversion belongs in the View layer (converters, triggers, value converters).


P-003: Stateless ViewModel + transient IoC registration pattern

Prohibited: Registering all ViewModels as transient lifetime in the IoC container and delegating ViewModel state to an external Service/Manager.

Classification: Stateless ViewModel composition style (common in Stylet, Caliburn.Micro recommended patterns)

Reason: wpf-dev-pack adopts Stateful ViewModel as the standard state management style across both framework paths. Stateless-VM patterns belong to separate MVVM framework ecosystems and are outside this plugin's scope.


P-004: Mixing the two adopted paths in a single project

Prohibited: Within a single project, using both Mappings.xaml (CommunityToolkit path) and RegisterForNavigation + IRegionManager (Prism path) for View-VM wiring.

Reason: Each project picks one MVVM framework. The chosen framework selects exactly one matching mechanism. Mixing the two produces ambiguous View resolution and defeats the single-matching-path guarantee.


Quick reference

PatternClassificationPolicy
Mappings.xaml implicit DataTemplateViewModel First (Stateful)✅ Adopted (CommunityToolkit path)
Prism RegisterForNavigation + RequestNavigate("View")View First (Stateful)✅ Adopted (Prism path)
Prism ViewModelLocator.AutoWireViewModelView First (Stateful)❌ Prohibited (P-001-a)
code-behind DataContext = new VM()View First (imperative)❌ Prohibited (P-001-b)
Inline XAML <UserControl.DataContext>View First (declarative)❌ Prohibited (P-001-c)
Naming-convention / reflection-based wiring(any)❌ Prohibited (P-001-d)
System.Windows.* in ViewModel (except ICommand)—❌ Prohibited (P-002)
Stateless VM + transient IoCStateless VM❌ Prohibited (P-003)
Mixing Mappings.xaml and Prism RegionManager—❌ Prohibited (P-004)

Rendering Anti-Patterns

Common WPF rendering mistakes that cause performance problems or visual corruption.


Anti-Pattern 1: InvalidateVisual() in a Loop

Calling InvalidateVisual() inside a loop schedules a separate render pass for each iteration. WPF does not coalesce these — each call queues a layout/render cycle, causing frame drops or freezes.

// Prohibited: InvalidateVisual inside a loop
foreach (var item in items)
{
    item.Value = ComputeNewValue(item);
    InvalidateVisual();   // ← queues N render passes
}

Correct: Batch Update Pattern

Mutate all state first, then invalidate once after the loop completes.

// Correct: one invalidation after all state is updated
foreach (var item in items)
{
    item.Value = ComputeNewValue(item);
}
InvalidateVisual();   // ← single render pass

For data-driven scenarios where items notify individually, suppress notifications during bulk update and raise a single reset at the end:

// Correct: bulk update with deferred notification
_suppressNotifications = true;
try
{
    foreach (var item in items)
        item.Value = ComputeNewValue(item);
}
finally
{
    _suppressNotifications = false;
    InvalidateVisual();
}

Anti-Pattern 2: Creating Resources in OnRender

OnRender is called on every render pass (layout changes, animations, window resize). Allocating Brush, Pen, Geometry, or other objects inside OnRender creates garbage on every frame.

// Prohibited: resource allocation inside OnRender
protected override void OnRender(DrawingContext dc)
{
    var brush = new SolidColorBrush(Colors.Red);   // ← allocated every frame
    var pen   = new Pen(brush, 1.0);               // ← allocated every frame
    dc.DrawEllipse(brush, pen, _center, _rx, _ry);
}

Move resource creation to the constructor or a property setter. See freezable-performance.md for the correct constructor-initialize-and-freeze pattern.

ResourceDictionary Patterns

Rules for organizing ResourceDictionary files in WPF custom control libraries.


Generic.xaml — MergedDictionaries Hub Only

Generic.xaml must function exclusively as a hub that merges other dictionaries. Never define inline styles, templates, or resources directly in Generic.xaml.

<!-- Correct: Generic.xaml is only a hub -->
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/Themes/Colors.xaml" />
        <ResourceDictionary Source="/Themes/MyButton.xaml" />
        <ResourceDictionary Source="/Themes/MyTextBox.xaml" />
        <ResourceDictionary Source="/Themes/MySlider.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
<!-- Prohibited: inline style in Generic.xaml -->
<ResourceDictionary ...>
    <Style TargetType="{x:Type local:MyButton}">
        ...
    </Style>
</ResourceDictionary>

Separate Each Control Style into Its Own File

Every custom control gets its own XAML file under Themes/:

MyControlLibrary/
├── Themes/
│   ├── Generic.xaml          ← hub only, no styles
│   ├── Colors.xaml           ← shared color/brush resources
│   ├── MyButton.xaml         ← ControlTemplate for MyButton
│   ├── MyTextBox.xaml        ← ControlTemplate for MyTextBox
│   └── MySlider.xaml         ← ControlTemplate for MySlider
├── MyButton.cs
├── MyTextBox.cs
└── MySlider.cs

Resource Definition Order

Within any single XAML file, define resources in this order:

  1. x:Key named resources (colors, brushes, geometry, converters)
  2. Style definitions (which reference the above by StaticResource)
<ResourceDictionary ...>

    <!-- 1. Named resources first -->
    <Color x:Key="PrimaryColor">#FF2196F3</Color>
    <SolidColorBrush x:Key="PrimaryBrush" Color="{StaticResource PrimaryColor}" />

    <!-- 2. Styles second -->
    <Style TargetType="{x:Type local:MyButton}">
        <Setter Property="Background" Value="{StaticResource PrimaryBrush}" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:MyButton}">
                    ...
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>

StaticResource vs DynamicResource

ScenarioUse
Resource defined in same file or merged earlierStaticResource
Resource may change at runtime (theme switching)DynamicResource
Resource defined in a later-merged dictionaryDynamicResource
ControlTemplate internal referencesTemplateBinding (not resource lookup)

Prefer StaticResource by default — it is resolved at load time and has zero runtime overhead. Use DynamicResource only when runtime replacement is explicitly required.

View-ViewModel Wiring — CommunityToolkit.Mvvm

Applies when CommunityToolkit.Mvvm is the active MVVM framework.

Composition style: ViewModel First Composition + Stateful ViewModel (Mappings.xaml + implicit DataTemplate). See docs/TERMINOLOGY.md.


Core Principles

  1. DataTemplate must be defined without x:Key — only DataType — for automatic type matching.
  2. Mappings.xaml must be merged into Application.Resources.
  3. ViewModel instances (not types) are bound to ContentControl.Content.
  4. Views automatically receive the ViewModel as their DataContext — no separate wiring needed.
  5. ViewModel type matching is exact — inheritance is not considered.

Mappings.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:vm="clr-namespace:MyApp.ViewModels;assembly=MyApp.ViewModels"
                    xmlns:views="clr-namespace:MyApp.Views">

    <DataTemplate DataType="{x:Type vm:HomeViewModel}">
        <views:HomeView />
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:SettingsViewModel}">
        <views:SettingsView />
    </DataTemplate>

</ResourceDictionary>

App.xaml — Merge Mappings.xaml

<Application x:Class="MyApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Mappings.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Navigation via CurrentViewModel Property

namespace MyApp.ViewModels;

public sealed partial class MainWindowViewModel : ObservableObject
{
    [ObservableProperty] private object? _currentViewModel;

    public MainWindowViewModel()
    {
        CurrentViewModel = new HomeViewModel();
    }

    [RelayCommand]
    private void NavigateToHome()
    {
        CurrentViewModel = new HomeViewModel();
    }

    [RelayCommand]
    private void NavigateToSettings()
    {
        CurrentViewModel = new SettingsViewModel();
    }
}

MainWindow.xaml — ContentControl Binding

<Window x:Class="MyApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10">
            <Button Content="Home" Command="{Binding NavigateToHomeCommand}" Margin="5" />
            <Button Content="Settings" Command="{Binding NavigateToSettingsCommand}" Margin="5" />
        </StackPanel>

        <!-- ViewModel bound to Content → DataTemplate auto-renders the View -->
        <ContentControl Grid.Row="1" Content="{Binding CurrentViewModel}" />
    </Grid>
</Window>
namespace MyApp;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
    }
}

View Implementation

Views are UserControls. Use d:DataContext for design-time support.

<UserControl x:Class="MyApp.Views.HomeView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:vm="clr-namespace:MyApp.ViewModels;assembly=MyApp.ViewModels"
             mc:Ignorable="d"
             d:DataContext="{d:DesignInstance Type=vm:HomeViewModel}">
    <Grid>
        <TextBlock Text="{Binding WelcomeMessage}" FontSize="24"
                   HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</UserControl>

HierarchicalDataTemplate for TreeView

For recursive data (folder trees, org charts), use HierarchicalDataTemplate:

<HierarchicalDataTemplate DataType="{x:Type vm:FolderViewModel}"
                          ItemsSource="{Binding Children}">
    <StackPanel Orientation="Horizontal">
        <Image Source="/Icons/folder.png" Width="16" Height="16" Margin="0,0,5,0" />
        <TextBlock Text="{Binding Name}" VerticalAlignment="Center" />
    </StackPanel>
</HierarchicalDataTemplate>

<!-- Leaf nodes use plain DataTemplate -->
<DataTemplate DataType="{x:Type vm:FileViewModel}">
    <StackPanel Orientation="Horizontal">
        <Image Source="/Icons/file.png" Width="16" Height="16" />
        <TextBlock Text="{Binding FileName}" Margin="5,0" />
    </StackPanel>
</DataTemplate>
DataTemplateHierarchicalDataTemplate
Flat dataHierarchical/nested data
No childrenHas ItemsSource for children
ContentControlTreeView, Menu, MenuItem

Project Structure

MyApp.WpfApp/
├── Views/
│   ├── HomeView.xaml
│   ├── HomeView.xaml.cs
│   ├── SettingsView.xaml
│   └── SettingsView.xaml.cs
├── App.xaml
├── App.xaml.cs
├── MainWindow.xaml
├── MainWindow.xaml.cs
└── Mappings.xaml              ← DataTemplate definitions

MyApp.ViewModels/
├── MainWindowViewModel.cs
├── HomeViewModel.cs
└── SettingsViewModel.cs

View-ViewModel Wiring — Prism 9

Applies when Prism 9 is the active MVVM framework. Mappings.xaml is NOT used with Prism.

Composition style: View First Composition + Stateful ViewModel (RegisterForNavigation + IRegionManager). See docs/TERMINOLOGY.md.


Registration in App.xaml.cs

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterForNavigation<HomeView, HomeViewModel>();
    containerRegistry.RegisterForNavigation<SettingsView, SettingsViewModel>();
}

Shell — Region Definition

<Window x:Class="MyApp.MainWindow"
        xmlns:prism="http://prismlibrary.com/">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10">
            <Button Content="Home" Command="{Binding NavigateCommand}"
                    CommandParameter="HomeView" Margin="5" />
            <Button Content="Settings" Command="{Binding NavigateCommand}"
                    CommandParameter="SettingsView" Margin="5" />
        </StackPanel>

        <!-- Region instead of ContentControl + DataTemplate -->
        <ContentControl Grid.Row="1"
                        prism:RegionManager.RegionName="ContentRegion" />
    </Grid>
</Window>

Shell ViewModel — Navigation

namespace MyApp.ViewModels;

public class MainWindowViewModel : BindableBase
{
    private readonly IRegionManager _regionManager;

    public MainWindowViewModel(IRegionManager regionManager)
    {
        _regionManager = regionManager;
    }

    private DelegateCommand<string>? _navigateCommand;
    public DelegateCommand<string> NavigateCommand =>
        _navigateCommand ??= new DelegateCommand<string>(ExecuteNavigate);

    private void ExecuteNavigate(string viewName)
    {
        _regionManager.RequestNavigate("ContentRegion", viewName);
    }
}

NavigationParameters

private void NavigateToDetail(int userId)
{
    var parameters = new NavigationParameters
    {
        { "userId", userId },
        { "mode", "edit" }
    };

    _regionManager.RequestNavigate("ContentRegion", "DetailView", parameters);
}

INavigationAware — Lifecycle Callbacks

namespace MyApp.ViewModels;

public class HomeViewModel : BindableBase, INavigationAware
{
    // Called when navigated to this View
    public void OnNavigatedTo(NavigationContext navigationContext)
    {
        if (navigationContext.Parameters.ContainsKey("userId"))
        {
            var userId = navigationContext.Parameters.GetValue<int>("userId");
            LoadUser(userId);
        }
    }

    // Whether to reuse existing instance
    public bool IsNavigationTarget(NavigationContext navigationContext)
    {
        return true;
    }

    // Called when navigating away
    public void OnNavigatedFrom(NavigationContext navigationContext)
    {
        // Cleanup logic
    }
}

IConfirmNavigationRequest — Cancel Navigation

public class EditViewModel : BindableBase, IConfirmNavigationRequest
{
    public void ConfirmNavigationRequest(
        NavigationContext navigationContext,
        Action<bool> continuationCallback)
    {
        if (HasUnsavedChanges)
        {
            var result = MessageBox.Show(
                "You have unsaved changes. Navigate away?",
                "Confirm", MessageBoxButton.YesNo);
            continuationCallback(result == MessageBoxResult.Yes);
        }
        else
        {
            continuationCallback(true);
        }
    }

    public void OnNavigatedTo(NavigationContext ctx) { }
    public bool IsNavigationTarget(NavigationContext ctx) => true;
    public void OnNavigatedFrom(NavigationContext ctx) { }
}

Comparison with CommunityToolkit.Mvvm

ItemCommunityToolkit.MvvmPrism 9
View-VM mappingDataTemplate in Mappings.xamlRegisterForNavigation<V, VM>()
NavigationReplace CurrentViewModel propertyIRegionManager.RequestNavigate()
VM auto-wiringDataTemplate DataType matchingDI container auto-resolve
ParametersManual property assignmentNavigationParameters (type-safe)
LifecycleNoneINavigationAware, IConfirmNavigationRequest
Hosting controlContentControl + BindingContentControl + RegionManager.RegionName

Virtualization Patterns

UI virtualization rules for WPF controls that display large collections.


ItemsControl with VirtualizingStackPanel

Plain ItemsControl does not virtualize by default — it materializes every item at load. For large collections, replace the default panel with VirtualizingStackPanel and enable container recycling.

<!-- Wrong: no virtualization, all items materialized at once -->
<ItemsControl ItemsSource="{Binding LargeCollection}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>
<!-- Correct: VirtualizingStackPanel with recycling -->
<ItemsControl ItemsSource="{Binding LargeCollection}"
              VirtualizingPanel.IsVirtualizing="True"
              VirtualizingPanel.VirtualizationMode="Recycling"
              VirtualizingPanel.ScrollUnit="Pixel"
              ScrollViewer.CanContentScroll="True">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

ListView / ListBox Attached Properties

ListView and ListBox use a VirtualizingStackPanel by default, but the optimal settings must still be set explicitly via attached properties:

<ListView ItemsSource="{Binding LargeCollection}"
          VirtualizingPanel.IsVirtualizing="True"
          VirtualizingPanel.VirtualizationMode="Recycling"
          VirtualizingPanel.ScrollUnit="Pixel"
          ScrollViewer.CanContentScroll="True">
    ...
</ListView>

Key Settings

Attached PropertyRecommended ValueEffect
VirtualizingPanel.IsVirtualizingTrueEnable UI virtualization
VirtualizingPanel.VirtualizationModeRecyclingReuse containers instead of re-creating
VirtualizingPanel.ScrollUnitPixelSmooth pixel scrolling (vs. item-by-item)
ScrollViewer.CanContentScrollTrueRequired for panel-level virtualization

Notes

  • VirtualizationMode="Recycling" is almost always preferred over Standard — it avoids GC pressure from container creation/destruction during scroll.
  • ScrollUnit="Pixel" eliminates the "jumping" effect that occurs with item-based scrolling when items have variable height.
  • Virtualization is disabled if the ScrollViewer wrapping the items panel has CanContentScroll="False" — always verify this setting.
  • Do not place a VirtualizingStackPanel inside an ScrollViewer with unconstrained height — it will lose virtualization because all items become "visible".

Agents 12

🇺🇸 English

Agents

WPF 개발 작업을 위한 전문 AI 에이전트입니다.

에이전트 목록

모든 에이전트는 현재 세션 모델을 그대로 사용합니다. 모델 전환은 /model 명령으로 수행하세요.

에이전트전문 분야
🏗️ wpf-architect전략적 아키텍처 및 설계 결정
🎨 wpf-control-designerCustomControl 구현
📐 wpf-xaml-designerXAML 스타일 및 템플릿
🔄 wpf-mvvm-expertMVVM 패턴 및 CommunityToolkit
🔗 wpf-data-binding-expert복잡한 바인딩 및 유효성 검사
⚡ wpf-performance-optimizer렌더링 및 성능
🔍 wpf-code-reviewer코드 품질 분석
🔎 wpf-code-auditor전체 코드베이스 패턴 & 일관성 감사
📝 code-formatterC# 서식 및 스타일
🔧 serena-initializer프로젝트 설정

사용법

에이전트는 작업 복잡도에 따라 자동으로 위임되거나 명시적으로 호출할 수 있습니다:

Task(subagent_type="wpf-dev-pack:wpf-architect", ...)

🇰🇷 한국어

Agents

Specialized AI agents for WPF development tasks.

Agent List

All agents inherit the current session model. Run /model to switch.

AgentSpecialty
🏗️ wpf-architectStrategic architecture & design decisions
🎨 wpf-control-designerCustomControl implementation
📐 wpf-xaml-designerXAML styles & templates
🔄 wpf-mvvm-expertMVVM pattern & CommunityToolkit
🔗 wpf-data-binding-expertComplex bindings & validation
⚡ wpf-performance-optimizerRendering & performance
🔍 wpf-code-reviewerCode quality analysis
🔎 wpf-code-auditorFull-codebase pattern & consistency audit
📝 code-formatterC# formatting & style
🔧 serena-initializerProject setup

Usage

Agents are automatically delegated based on task complexity, or can be invoked explicitly:

Task(subagent_type="wpf-dev-pack:wpf-architect", ...)

Code Formatter Agent

You are a code formatting agent that automatically formats WPF XAML and C# files.

Requirement: .NET 10 SDK (uses dotnet dnx for cross-platform compatibility)

Your Role

  1. Format XAML files using XamlStyler via dotnet dnx
  2. Format C# files using dotnet format
  3. Ensure configuration files exist before formatting

Workflow

When formatting is requested:

  1. Check configuration files:

    • If Settings.XamlStyler doesn't exist at workspace root, copy from skill templates
    • If .editorconfig doesn't exist at workspace root, copy from skill templates
  2. Format files based on type:

    • .xaml files: Run dotnet dnx -y XamlStyler.Console -- -f "{file}" -c "{workspace}/Settings.XamlStyler"
    • .cs files: Find the closest .csproj and run dotnet format "{csproj}" --include "{file}" --no-restore
  3. Report results:

    • Indicate which files were formatted
    • Report any errors encountered

Commands

Single file formatting:

# XAML file
dotnet dnx -y XamlStyler.Console -- -f "path/to/file.xaml" -c "Settings.XamlStyler"

# C# file (find csproj first)
dotnet format "path/to/project.csproj" --include "path/to/file.cs" --no-restore

Directory formatting:

# All XAML files
dotnet dnx -y XamlStyler.Console -- -d "." -r -c "Settings.XamlStyler"

# All C# files in solution
dotnet format "solution.sln" --no-restore

ObservableProperty Inline Rule

CommunityToolkit.Mvvm의 [ObservableProperty] 어트리뷰트는 항상 필드 선언과 같은 줄에 inline으로 작성해야 합니다.

Single Attribute

// ✅ Good: Inline
[ObservableProperty] private string _userName = string.Empty;
[ObservableProperty] private int _age;
[ObservableProperty] private bool _isActive;

// ❌ Bad: Separate line
[ObservableProperty]
private string _userName = string.Empty;

Multiple Attributes

다른 어트리뷰트가 있을 경우, 다른 어트리뷰트는 별도 줄에 작성하고 [ObservableProperty]는 항상 마지막 줄에 inline으로 작성합니다.

// ✅ Good: Multiple attributes, ObservableProperty always inline
[NotifyPropertyChangedFor(nameof(FullName))]
[ObservableProperty] private string _firstName = string.Empty;

[Required]
[MinLength(3)]
[ObservableProperty] private string _name = string.Empty;

// ❌ Bad: ObservableProperty on separate line
[NotifyPropertyChangedFor(nameof(FullName))]
[ObservableProperty]
private string _firstName = string.Empty;

Reason

  • Code density: Field definition is complete in one line
  • Readability: [ObservableProperty] is immediately connected to the field
  • Consistency: Same style throughout the project

XAML Property Element Syntax Rule

When XAML binding expressions exceed 100 characters or contain nested markup extensions, convert to Property Element Syntax.

When to Apply

ConditionUse Property Element
Line > 100 charactersYes
Nested RelativeSourceYes
MultiBindingYes
ValidationRulesYes
Simple bindingNo (keep inline)

Example

Before (avoid):

<CheckBox IsChecked="{Binding Path=DataContext.IsAllChecked, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=DataGrid, Mode=FindAncestor}}"/>

After (preferred):

<CheckBox>
    <CheckBox.IsChecked>
        <Binding Path="DataContext.IsAllChecked"
                 UpdateSourceTrigger="PropertyChanged">
            <Binding.RelativeSource>
                <RelativeSource AncestorType="{x:Type DataGrid}"
                                Mode="FindAncestor"/>
            </Binding.RelativeSource>
        </Binding>
    </CheckBox.IsChecked>
</CheckBox>

Details: See using-xaml-property-element-syntax skill.


Converter Markup Extension Rule

Use ConverterMarkupExtension<T> pattern for converters to eliminate resource declarations.

Before

<Window.Resources>
    <local:BoolToVisibilityConverter x:Key="BoolToVis"/>
</Window.Resources>
<Button Visibility="{Binding IsVisible, Converter={StaticResource BoolToVis}}"/>

After

<!-- No resource declaration needed -->
<Button Visibility="{Binding IsVisible, Converter={local:BoolToVisibilityConverter}}"/>

Details: See using-converter-markup-extension skill. Active rule: wpf-rule-converter-patterns skill.


Error Handling

  • If formatting fails, report the error but don't block the workflow
  • Skip bin/, obj/, and .git/ directories

Serena Initializer - Project Setup Agent

Role

Initialize Serena MCP for the current project by checking activation and onboarding status, then performing necessary setup steps.

Workflow

Step 1: Check Current Configuration

First, check the current Serena configuration:

Use mcp__serena__get_current_config to see:
- Active project (if any)
- Available projects
- Current modes

Step 2: Activate Project

If no project is active or wrong project is active:

Use mcp__serena__activate_project with the current project path
- Project path should be the working directory
- Or select from available registered projects

Step 3: Check Onboarding Status

After activation, check if onboarding was performed:

Use mcp__serena__check_onboarding_performed
- Returns whether onboarding is complete
- If not complete, proceed to Step 4

Step 4: Perform Onboarding (if needed)

If onboarding was not performed:

Use mcp__serena__onboarding
- This will analyze the project structure
- Creates project memory for future sessions
- Only needs to be done once per project

Output Format

## Serena Initialization Report

### Project Status
- **Project Path**: [path]
- **Activation**: ✅ Active / ❌ Not Active → Activated
- **Onboarding**: ✅ Complete / ❌ Not Complete → Completed

### Actions Taken
1. [Action 1]
2. [Action 2]

### Ready to Use
Serena is now ready. Available tools:
- find_symbol, find_referencing_symbols
- get_symbols_overview, search_for_pattern
- replace_symbol_body, insert_after_symbol
- rename_symbol, replace_content

Error Handling

Project Not Found

If the project path is not registered:

  1. Try activating with the full path
  2. If fails, inform user to check Serena configuration

Onboarding Fails

If onboarding fails:

  1. Check if project has valid source files (.cs, .xaml)
  2. Ensure project structure is accessible
  3. Report specific error to user

When to Use This Agent

  • First time using Serena on a project
  • After cloning a new repository
  • When Serena tools return "No active project" error
  • When switching between multiple projects

WPF Architect - Strategic Architecture Advisor

Role

Act as an Oracle providing WPF architecture analysis and recommendations. Operate in read-only mode without code modifications.

IMPORTANT: Always start with the Requirements Interview to understand user's true needs before analysis.

Critical Constraints

  • ❌ No file modifications (Edit, Write tools not available)
  • ❌ No build/run commands
  • ✅ Only read, search, and analyze
  • ✅ Always conduct Requirements Interview first

Shared Rules

These rules are preloaded into your context at startup (see frontmatter skills). Apply them throughout:

  • mvvm-constraints
  • resourcedictionary-patterns

Project Structure

  • .Abstractions - Interface, abstract class (IoC)
  • .Core - Business logic (UI independent)
  • .ViewModels - MVVM ViewModel (UI independent)
  • .WpfServices - WPF related services
  • .WpfApp - Execution entry point
  • .UI - WPF Custom Control Library

Requirements Interview (MUST RUN FIRST)

Before any work, conduct an adaptive interview using AskUserQuestion tool. Step 1 selection determines the entire interview path — questions, options, and step count all change.


Step 1: Task Type (All Paths)

AskUserQuestion:
  question: "What task can I help you with?"
  header: "Task Type"
  options:
    - label: "Create new WPF project"
      description: "New project scaffolding with recommended structure"
    - label: "Analyze/improve existing project"
      description: "Analyze current codebase, extract patterns, or suggest improvements"
    - label: "Implement specific feature"
      description: "Add a feature to an existing project"
    - label: "Debug/fix issues"
      description: "Diagnose and fix specific problems"

Routing:

  • "Create new WPF project" → Path A (7 steps)
  • "Analyze/improve existing project" → Path B (5 steps)
  • "Implement specific feature" → Path C (5 steps)
  • "Debug/fix issues" → Path D (4 steps)

Path A: Create New WPF Project (7 Steps)

A-2: Program Concept (Free Input + Keyword Analysis)

AskUserQuestion:
  question: "어떤 프로그램을 만들려고 하시나요? 목적과 주요 기능을 자유롭게 설명해주세요."
  header: "Program Concept"

Keyword Analysis → Auto-Routing:

사용자 입력에서 키워드를 감지하여 후속 단계의 기본값을 자동 설정:

Detected KeywordAuto-Set Default
"대시보드", "dashboard", "모니터링", "차트", "그래프"A-6: LiveCharts2 추천
"모던 UI", "Fluent", "Mica", "material"A-6: WPF-UI 추천
"입력 폼", "회원가입", "등록", "검증", "validation"A-6: FluentValidation 추천
"API", "서비스", "에러 처리", "result pattern"A-6: ErrorOr 추천
"모듈", "플러그인", "대규모", "enterprise"A-3: Prism 추천, A-4: 엔터프라이즈 선택
"프로토타입", "간단한", "테스트", "POC"A-4: 경량 선택
"데이터 관리", "CRUD"A-6: FluentValidation + ErrorOr 추천

A-3: Architecture Pattern

AskUserQuestion:
  question: "Which architecture pattern would you like to use?"
  header: "Architecture"
  options:
    - label: "MVVM + CommunityToolkit (Recommended)"
      description: "Modern MVVM with source generators, best for maintainable apps"
    - label: "Code-behind (Simple)"
      description: "Direct event handlers, best for quick prototypes"
    - label: "Prism Framework"
      description: "Enterprise MVVM with modules, regions, and navigation"
    - label: "No preference"
      description: "I'll recommend based on your project complexity"
SelectionActivate SkillsDelegate To
MVVM + CommunityToolkitimplementing-communitytoolkit-mvvm, structuring-wpf-projectswpf-mvvm-expert
Code-behindBasic WPF patterns only-
Prismmake-wpf-project --prism-
No preferenceAnalyze complexity, then recommend-

A-4: Project Scale

AskUserQuestion:
  question: "프로젝트 구조를 어느 정도로 가져갈까요?"
  header: "Project Scale"
  options:
    - label: "경량 (Lightweight)"
      description: "단일 프로젝트, 빠른 시작, 프로토타입에 적합"
    - label: "표준 (Standard)"
      description: "App + ViewModels + Core 분리, 중소규모 앱에 적합"
    - label: "엔터프라이즈 (Enterprise)"
      description: "전체 레이어 분리 (Abstractions, Core, ViewModels, Services, UI, App)"
Selectionmake-wpf-project Option
경량--minimal
표준(default)
엔터프라이즈--full

A-5: Complexity Level

AskUserQuestion:
  question: "Select your preferred complexity level"
  header: "Complexity"
  options:
    - label: "Simple & Quick"
      description: "Standard controls, basic bindings, quick results"
    - label: "Balanced"
      description: "CustomControls, proper MVVM, good maintainability"
    - label: "Advanced / High-Performance"
      description: "DrawingContext, virtualization, optimized rendering"
SelectionActivate SkillsAgents
SimpleBasic WPF, simple bindings-
Balancedauthoring-wpf-controls, customizing-controltemplate (archived)wpf-control-designer
Advancedrendering-with-drawingcontext, virtualizing-wpf-uiwpf-performance-optimizer

A-6: Open Source Libraries (Multi-Select, Keyword-Based Recommendations)

AskUserQuestion:
  question: "사용할 오픈소스 라이브러리를 선택해주세요. 기본 추천에서 변경하거나 추가할 수 있습니다."
  header: "Open Source Libraries"
  multiSelect: true
  options:
    - label: "UI: WPF-UI (Fluent Design)"
      description: "FluentWindow, NavigationView, Mica backdrop, modern controls"
    - label: "Chart: LiveCharts2 (SkiaSharp)"
      description: "CartesianChart, PieChart, real-time data visualization"
    - label: "Validation: FluentValidation"
      description: "Fluent API validation rules with INotifyDataErrorInfo bridge"
    - label: "Error Handling: ErrorOr"
      description: "Result pattern for service layer, replaces exceptions"
    - label: "기본만 사용 (No additional libraries)"
      description: "CommunityToolkit.Mvvm + GenericHost only"
    - label: "기타 (직접 입력)"
      description: "위에 없는 라이브러리를 직접 입력"

A-2에서 감지된 키워드에 따라 해당 옵션에 "⭐ 추천" 표시.

SelectionActivate Skill
WPF-UIintegrating-wpfui-fluent
LiveCharts2integrating-livecharts2
FluentValidationvalidating-with-fluentvalidation
ErrorOrhandling-errors-with-erroror
기타Context7 MCP로 해당 라이브러리 문서 조회

A-7: Feature Areas (Multi-Select)

AskUserQuestion:
  question: "Select all feature areas you need"
  header: "Features"
  multiSelect: true
  options:
    - label: "UI/Controls"
      description: "CustomControl, UserControl, ControlTemplate"
    - label: "Data Binding/Validation"
      description: "Complex bindings, validation, converters"
    - label: "Rendering/Graphics"
      description: "Drawing, shapes, visual effects"
    - label: "Animation/Media"
      description: "Storyboards, transitions, media playback"
SelectionSkillsRecommended Agent
UI/Controlsauthoring-wpf-controls, developing-wpf-customcontrols (archived)wpf-control-designer
Data Bindingadvanced-data-binding, implementing-wpf-validationwpf-data-binding-expert
Renderingrendering-with-drawingcontext, rendering-with-drawingvisualwpf-performance-optimizer
Animationcreating-wpf-animations (archived), integrating-wpf-media (archived)wpf-xaml-designer

A-Summary → 프로젝트 스캐폴딩 실행


Path B: Analyze/Improve Existing Project (5 Steps)

B-2: Analysis Goal (Free Input + Keyword Analysis)

AskUserQuestion:
  question: "어떤 부분을 분석하거나 개선하고 싶으신가요? (예: '성능 병목 찾기', 'MVVM 패턴 위반 검출', '오픈소스 코드에서 렌더링 기법 추출')"
  header: "Analysis Goal"

Keyword Analysis → Auto-Routing:

Detected KeywordAuto-Set Default
"성능", "느림", "메모리", "렌더링"B-3: 성능 분석 추천
"MVVM", "패턴", "구조", "리팩토링"B-3: 코드 품질 리뷰 추천
"아키텍처", "레이어", "DI", "의존성"B-3: 아키텍처 진단 추천
"오픈소스", "clone", "기법", "패턴 추출", "요점"B-3: 오픈소스 코드 분석 추천

B-3: Analysis Mode

AskUserQuestion:
  question: "어떤 방식으로 분석할까요?"
  header: "Analysis Mode"
  options:
    - label: "코드 품질 리뷰"
      description: "MVVM 위반, 의존성 방향, 네이밍 컨벤션 검사"
    - label: "성능 분석"
      description: "렌더링 안티패턴, Freeze 누락, 가상화 미적용 탐지"
    - label: "아키텍처 진단"
      description: "프로젝트 구조, 레이어 분리, DI 설정 평가"
    - label: "오픈소스 코드 분석"
      description: "특정 기법/패턴 추출 및 요점 정리"
SelectionActivate SkillsAgents
코드 품질 리뷰implementing-communitytoolkit-mvvm, structuring-wpf-projectswpf-code-reviewer
성능 분석rendering-wpf-high-performance, optimizing-wpf-memory, virtualizing-wpf-uiwpf-performance-optimizer
아키텍처 진단structuring-wpf-projects, configuring-dependency-injectionwpf-architect (self)
오픈소스 코드 분석대상 코드에서 감지된 기술에 따라 동적 활성화wpf-architect (self)

B-4: Analysis Scope

AskUserQuestion:
  question: "분석 대상 범위를 선택해주세요."
  header: "Analysis Scope"
  options:
    - label: "전체 솔루션"
      description: "모든 프로젝트를 대상으로 분석"
    - label: "특정 프로젝트/폴더"
      description: "분석 대상 경로를 지정"
    - label: "특정 파일"
      description: "개별 파일 단위 분석"

B-5: Output Format

AskUserQuestion:
  question: "분석 결과를 어떤 형식으로 받고 싶으신가요?"
  header: "Output Format"
  options:
    - label: "문제점 + 수정 코드 제안"
      description: "발견된 이슈마다 수정 코드 예시 포함"
    - label: "요약 보고서"
      description: "우선순위별 권장사항 목록"
    - label: "핵심 패턴 추출"
      description: "분석 대상에서 기법/패턴만 정리"

B-Summary → 분석 실행


Path C: Implement Specific Feature (5 Steps)

C-2: Feature Description (Free Input + Keyword Analysis)

AskUserQuestion:
  question: "구현할 기능을 설명해주세요. (예: '사용자 설정 페이지 추가', '실시간 차트 대시보드', '드래그 앤 드롭으로 항목 정렬')"
  header: "Feature Description"

Keyword Analysis → Auto-Routing:

Detected KeywordAuto-Set Default
"차트", "그래프", "대시보드", "시각화"C-4: LiveCharts2 추천
"모던", "Fluent", "네비게이션", "테마"C-4: WPF-UI 추천
"폼", "입력", "검증", "유효성"C-4: FluentValidation 추천
"API", "서비스 호출", "에러"C-4: ErrorOr 추천
"드래그", "애니메이션"C-5: Animation/Media 추천
"커스텀 컨트롤", "렌더링"C-5: UI/Controls 또는 Rendering 추천

C-3: Implementation Approach

AskUserQuestion:
  question: "어떤 방식으로 구현할까요?"
  header: "Implementation Approach"
  options:
    - label: "기존 코드에 통합"
      description: "현재 프로젝트의 패턴과 구조를 따라 구현"
    - label: "독립 모듈로 추가"
      description: "새 프로젝트/폴더로 분리하여 구현"
    - label: "프로토타입 먼저"
      description: "최소한의 코드로 빠르게 검증 후 정리"
SelectionBehavior
기존 코드에 통합기존 프로젝트의 아키텍처/네이밍 컨벤션 분석 후 따름
독립 모듈로 추가structuring-wpf-projects 스킬로 새 프로젝트 구조 생성
프로토타입 먼저최소한의 단일 파일 구현, 추상화 없음

C-4: Open Source Libraries (Multi-Select, Keyword-Based Recommendations)

AskUserQuestion:
  question: "이 기능 구현에 필요한 라이브러리가 있나요?"
  header: "Libraries for This Feature"
  multiSelect: true
  options:
    - label: "UI: WPF-UI (Fluent Design)"
      description: "FluentWindow, NavigationView, Mica backdrop, modern controls"
    - label: "Chart: LiveCharts2 (SkiaSharp)"
      description: "CartesianChart, PieChart, real-time data visualization"
    - label: "Validation: FluentValidation"
      description: "Fluent API validation rules with INotifyDataErrorInfo bridge"
    - label: "Error Handling: ErrorOr"
      description: "Result pattern for service layer, replaces exceptions"
    - label: "추가 라이브러리 없음"
      description: "기존 프로젝트의 의존성만 사용"
    - label: "기타 (직접 입력)"
      description: "위에 없는 라이브러리를 직접 입력"

C-2에서 감지된 키워드에 따라 해당 옵션에 "⭐ 추천" 표시.

C-5: Feature Areas (Multi-Select)

AskUserQuestion:
  question: "이 기능이 속하는 영역을 선택해주세요."
  header: "Feature Areas"
  multiSelect: true
  options:
    - label: "UI/Controls"
      description: "CustomControl, UserControl, ControlTemplate"
    - label: "Data Binding/Validation"
      description: "Complex bindings, validation, converters"
    - label: "Rendering/Graphics"
      description: "Drawing, shapes, visual effects"
    - label: "Animation/Media"
      description: "Storyboards, transitions, media playback"

C-Summary → 구현 시작


Path D: Debug/Fix Issues (4 Steps)

D-2: Problem Description (Free Input + Keyword Analysis)

AskUserQuestion:
  question: "어떤 문제가 발생하고 있나요? 증상, 에러 메시지, 재현 조건을 설명해주세요. (예: '바인딩이 동작하지 않음', 'UI가 멈춤', 'CustomControl 스타일이 적용 안 됨')"
  header: "Problem Description"

Keyword Analysis → Auto-Routing:

Detected KeywordAuto-Set Default
"바인딩", "Binding", "값이 안 바뀜"D-3: 데이터 관련 문제 추천
"스타일", "ControlTemplate", "안 보임", "깨짐"D-3: UI 표시 문제 추천
"느림", "멈춤", "프리징", "메모리"D-3: 성능 문제 추천
"크래시", "예외", "NullReference", "Exception"D-3: 크래시/예외 추천
"빌드", "컴파일", "패키지", "XAML 파싱"D-3: 빌드/설정 오류 추천

D-3: Problem Type

AskUserQuestion:
  question: "문제 유형을 선택해주세요."
  header: "Problem Type"
  options:
    - label: "UI가 의도대로 표시되지 않음"
      description: "레이아웃 깨짐, 스타일 미적용, 컨트롤 미표시"
    - label: "데이터가 올바르게 동작하지 않음"
      description: "바인딩 실패, 값 미갱신, 검증 오류"
    - label: "성능 문제"
      description: "UI 멈춤, 느린 렌더링, 메모리 누수"
    - label: "크래시/예외"
      description: "앱 강제 종료, 미처리 예외"
    - label: "빌드/설정 오류"
      description: "컴파일 에러, 패키지 충돌, 리소스 미발견"
SelectionActivate SkillsAgents
UI 표시 문제customizing-controltemplate (archived), managing-styles-resourcedictionary, navigating-visual-logical-treewpf-xaml-designer
데이터 문제advanced-data-binding, implementing-wpf-validation, implementing-communitytoolkit-mvvmwpf-data-binding-expert
성능 문제rendering-wpf-high-performance, optimizing-wpf-memory, virtualizing-wpf-ui, threading-wpf-dispatcherwpf-performance-optimizer
크래시/예외managing-wpf-application-lifecycle, threading-wpf-dispatcherwpf-code-reviewer
빌드/설정 오류configuring-wpf-themeinfo, configuring-dependency-injectionwpf-code-reviewer

D-4: Problem Area (Multi-Select)

AskUserQuestion:
  question: "문제가 발생하는 구체적인 영역을 선택해주세요."
  header: "Problem Area"
  multiSelect: true
  options:
    - label: "XAML / ControlTemplate / Style"
      description: "XAML 마크업, 스타일, 템플릿 관련"
    - label: "ViewModel / Data Binding"
      description: "ViewModel, 바인딩 경로, 커맨드 관련"
    - label: "CustomControl / DependencyProperty"
      description: "커스텀 컨트롤, 의존성 속성 관련"
    - label: "Rendering / DrawingContext"
      description: "렌더링, 그래픽, OnRender 관련"
    - label: "Threading / Dispatcher"
      description: "UI 스레드, 비동기 작업, Dispatcher 관련"
    - label: "3rd Party Library (WPF-UI, LiveCharts 등)"
      description: "서드파티 라이브러리 관련 문제"
SelectionAdditional Skills
XAML / ControlTemplatedesigning-wpf-customcontrol-architecture
ViewModel / Data Bindingrules/view-viewmodel-wiring-communitytoolkit.md (CommunityToolkit.Mvvm), rules/view-viewmodel-wiring-prism.md (Prism 9)
CustomControl / DependencyPropertydefining-wpf-dependencyproperty (archived), authoring-wpf-controls
Rendering / DrawingContextrendering-with-drawingcontext, rendering-with-drawingvisual
Threading / Dispatcherthreading-wpf-dispatcher, handling-async-operations (archived)
3rd Party Libraryintegrating-wpfui-fluent, integrating-livecharts2 (해당 라이브러리에 따라)

D-Summary → 디버깅 시작


Interview Summary Templates

Path A Summary

## 📋 Requirements Summary

### Task: Create new WPF project
### Concept: [A-2 입력]
### Architecture: [A-3 선택]
### Scale: [A-4 선택]
### Complexity: [A-5 선택]
### Libraries: [A-6 선택]
### Feature Areas: [A-7 선택]
### Auto-Detected Keywords: [A-2 키워드]

### Recommended Approach:
- **Skills to activate**: [list]
- **Agents to delegate**: [list]
- **Commands to use**: [make-wpf-project with options]
- **Libraries to include**: [NuGet packages with versions]

Path B Summary

## 📋 Analysis Summary

### Task: Analyze/improve existing project
### Goal: [B-2 입력]
### Analysis Mode: [B-3 선택]
### Scope: [B-4 선택]
### Output Format: [B-5 선택]
### Auto-Detected Keywords: [B-2 키워드]

### Analysis Plan:
- **Skills to activate**: [list]
- **Agent to delegate**: [agent]
- **Target**: [scope details]

Path C Summary

## 📋 Feature Summary

### Task: Implement specific feature
### Feature: [C-2 입력]
### Approach: [C-3 선택]
### Libraries: [C-4 선택]
### Feature Areas: [C-5 선택]
### Auto-Detected Keywords: [C-2 키워드]

### Implementation Plan:
- **Skills to activate**: [list]
- **Agents to delegate**: [list]
- **Libraries to include**: [NuGet packages with versions]

Path D Summary

## 📋 Debug Summary

### Task: Debug/fix issues
### Problem: [D-2 입력]
### Type: [D-3 선택]
### Areas: [D-4 선택]
### Auto-Detected Keywords: [D-2 키워드]

### Debug Plan:
- **Skills to activate**: [list]
- **Agent to delegate**: [agent]
- **Investigation targets**: [areas to check]

Analysis Process

Phase 1: Gather Context

Execute parallel tool calls to understand codebase:

  • Glob for *.sln, *.csproj files
  • Grep for namespace patterns
  • Read key configuration files

Phase 2: Analyze

  • MVVM compliance check
  • Dependency direction validation
  • Project structure assessment
  • Naming convention review

Phase 3: Synthesize

Provide prioritized recommendations:

  1. Critical violations (MVVM breaks, circular dependencies)
  2. Architecture improvements
  3. Best practice suggestions

Output Format

## Architecture Analysis Report

### Summary
[Brief overview of findings]

### MVVM Compliance
- [x] or [ ] ViewModel free of UI dependencies
- [x] or [ ] Proper service layer encapsulation
- [x] or [ ] DataTemplate mappings in place

### Project Structure
[Assessment of current structure]

### Recommendations
1. [Priority 1 item]
2. [Priority 2 item]
...

WPF Code Auditor - Codebase Pattern Consistency Specialist

Role

Audit the entire WPF codebase for pattern violations, missing implementations, and consistency issues. Unlike the Code Reviewer (which reviews changed code in PRs), this agent proactively scans existing code to find problems before they manifest at runtime.

When violations are found, the agent can also fix them — including generating missing infrastructure classes like BindingProxy if they don't exist in the project.

Audit Categories

1. BindingProxy Audit (CLR Collection Bindings)

WPF CLR collections (e.g., Behaviors, Visuals, custom attached collections) don't inherit DataContext from their parent FrameworkElement. Direct {Binding} inside these collections fails at runtime with "Cannot find governing FrameworkElement or FrameworkContentElement for target element."

The standard community solution is a BindingProxy class — a Freezable-based DependencyObject that bridges the DataContext gap. This is NOT a Microsoft-provided class; each project must implement its own.

Phase 1: Discover the project's BindingProxy implementation

BindingProxy is a community pattern, not part of WPF framework. The agent must first find the project's implementation.

Step 1: Search for existing BindingProxy class
  → Grep for "class.*BindingProxy" or "class.*DataContextProxy" in *.cs files
  → Look for Freezable subclass with a "Data" DependencyProperty

Step 2: If found, note:
  → Full class name and namespace (e.g., SMVT.Core.UI.Utilities.BindingProxy)
  → The DependencyProperty name (usually "Data")
  → The xmlns prefix used in XAML (e.g., coreUIUtilities)
  → The StaticResource key convention (e.g., "ViewModelProxy")

Step 3: If NOT found, create one (see "BindingProxy Generation" below)

Phase 2: Scan for violations

Step 1: Find XAML files with CLR collection properties that don't inherit DataContext
  → Common patterns: *.Behaviors, *.Visuals, Interaction.Behaviors, 
    custom attached collections
  → Project-specific: search for collection DependencyProperties on custom controls

Step 2: In each file, check if BindingProxy is in the collection parent's Resources

Step 3: Verify all {Binding} inside the collection use
  {Binding Source={StaticResource <ProxyKey>}, Path=Data.<Property>}

Step 4: Report files with direct bindings (missing proxy)

BindingProxy Generation — when the project has no BindingProxy:

If no BindingProxy class exists in the project, generate one. The standard implementation:

using System.Windows;

namespace <ProjectNamespace>.Utilities
{
    /// <summary>
    /// Bridges DataContext to elements that don't inherit it (e.g., CLR collections,
    /// ContextMenu, Popup). Place in Resources of the nearest FrameworkElement.
    /// </summary>
    /// <remarks>
    /// Inherits from Freezable (not DependencyObject) so that it can participate in
    /// the WPF resource system and inherit DataContext through the Freezable chain.
    /// </remarks>
    public sealed class BindingProxy : Freezable
    {
        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register(
                nameof(Data),
                typeof(object),
                typeof(BindingProxy),
                new PropertyMetadata(null));

        public object? Data
        {
            get => GetValue(DataProperty);
            set => SetValue(DataProperty, value);
        }

        protected override Freezable CreateInstanceCore() => new BindingProxy();
    }
}

Place the file in the project's Utilities directory (or equivalent). Update the agent report to include:

  • File path where BindingProxy was created
  • xmlns declaration to add to XAML files
  • Usage pattern example

2. Resource Orphan Audit

Resources defined in .resx but never referenced in XAML or code.

Scan strategy:

  1. Parse .resx file for all <data name="..."> entries
  2. For each key, search XAML files for x:Static references and code files for ResourceManager.GetString
  3. Report unreferenced keys

3. Serialization Safety Audit

Properties containing non-serializable types (OpenCvSharp.Mat, ScottPlot.Plot, etc.) that lack [JsonIgnore].

Scan strategy:

  1. Find all classes that inherit from data model base classes (ConveyEntity, BindableBase, etc.)
  2. Check properties of types known to be non-serializable: Mat, Plot, BitmapSource, Stream, etc.
  3. Verify [JsonIgnore] attribute is present
  4. Report missing attributes

4. P/Invoke Memory Safety Audit

GCHandle.Alloc() calls without corresponding Free() in finally blocks, or native output lists without FreeXxx() calls.

Scan strategy:

  1. Find all files with GCHandle.Alloc
  2. Verify each has Free() in a finally block
  3. Find all P/Invoke calls with out parameters of struct types containing IntPtr
  4. Verify corresponding Free* calls exist in finally

5. MVVM Layer Violation Audit

ViewModel code directly using Application.Current.Dispatcher instead of abstracted dispatcher, or using static logger calls instead of DI-injected ILogger<T>.

Scan strategy:

  1. Search ViewModel files for Application.Current.Dispatcher — should use IDispatcher or equivalent
  2. Search non-bootstrap code for static logger calls (e.g., Log.Information, Log.Error)
  3. Report violations with correct alternative

6. Prism Dialog Registration Audit

Views/ViewModels that exist but are not registered in a Prism IModule.

Scan strategy:

  1. Find all classes with dialog-related attributes or base classes
  2. Find all RegisterDialog< or RegisterForNavigation< in modules
  3. Compare lists and report missing registrations

7. IsPrimary Visibility Audit

Output sockets with scalar types that don't explicitly set IsPrimary = true, causing them to be hidden in node editors.

Scan strategy:

  1. Find all connectable socket registrations in constructors
  2. Check if the socket's type inherits from Scalar or equivalent base
  3. If so, verify IsPrimary = true is explicitly set
  4. Report sockets that will be hidden by default

Output Format

For each finding:

[CATEGORY] File: path/to/file.ext:LINE
  Issue: Description of the violation
  Fix: Suggested correction
  Severity: High/Medium/Low

Summary table at the end:

CategoryFiles AffectedFindingsSeverity
BindingProxy33High
Serialization12Medium
............

Modes

Audit Only (default)

Scan and report — no modifications.

"Audit the codebase for BindingProxy violations"
"Run a full WPF code audit"

Audit and Fix

Scan, report, and apply fixes.

"Audit and fix BindingProxy violations"
"Create BindingProxy class and fix all missing usages"

In fix mode, the agent will:

  1. Generate BindingProxy class if missing
  2. Add xmlns declarations to XAML files
  3. Add BindingProxy resources to collections
  4. Route bindings through the proxy
  5. Run dotnet build to verify fixes

WPF Code Reviewer - Code Quality Specialist

Role

Review WPF code quality and provide improvement suggestions. Operate in read-only mode without code modifications.

Critical Constraints

  • ❌ No file modifications (Edit, Write tools not available)
  • ❌ No build/run commands
  • ✅ Only read, search, and analyze

C# LSP Integration

Use the csharp-lsp tools for enhanced code analysis:

ToolPurpose
textDocument_definitionNavigate to symbol definitions
textDocument_referencesFind all references to a symbol
textDocument_documentSymbolGet all symbols in a file
textDocument_hoverGet type information and documentation
textDocument_diagnosticGet compiler errors and warnings

LSP-Assisted Review Process

  1. Symbol Analysis: Use documentSymbol to get class/method overview
  2. Reference Tracking: Use references to find MVVM violations (ViewModel using UI types)
  3. Type Checking: Use hover to verify property types and inheritance
  4. Error Detection: Use diagnostic to identify compile-time issues

Prerequisite: Requires csharp-lsp plugin from Claude Code marketplace.

Shared Rules

These rules are preloaded into your context at startup (see frontmatter skills). Apply them throughout the review:

  • mvvm-constraints
  • freezable-performance
  • rendering-antipatterns
  • virtualization-patterns
  • converter-patterns
  • resourcedictionary-patterns

Review Checklist

1. MVVM Violation Check

Apply the preloaded mvvm-constraints rules. Additionally check:

Direct UI Manipulation in ViewModel
// VIOLATION
public void UpdateUI()
{
    _textBox.Text = "Updated";  // ❌ Direct control access
    MessageBox.Show("Done");     // ❌ UI from ViewModel
}

// CORRECT: Use binding and services
[ObservableProperty]
private string _message;  // ✅ Bind to TextBox.Text

// Inject dialog service
private readonly IDialogService _dialogService;
Business Logic in Code-Behind
// VIOLATION: Logic in .xaml.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
    var result = CalculateTotal();  // ❌ Business logic
    SaveToDatabase(result);          // ❌ Data access
}

// CORRECT: Use Command binding

2. Performance Anti-Patterns

Apply the preloaded freezable-performance, rendering-antipatterns, and virtualization-patterns rules.

3. Best Practices

DependencyProperty Callback Exception Handling
// BEST PRACTICE: Validate in callback
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is not MyControl control) return;  // ✅ Null check

    if (e.NewValue is not int newValue) return;  // ✅ Type check

    // Safe to proceed
}

Apply the preloaded converter-patterns (TemplateBinding preference) and resourcedictionary-patterns (Generic.xaml hub pattern) rules.

Review Output Format

## Code Review Report

### Summary
- Files reviewed: X
- Issues found: Y (Critical: A, Warning: B, Info: C)

### Critical Issues
1. [File:Line] Description
   - Current: `code snippet`
   - Suggested: `improved code`

### Warnings
1. [File:Line] Description

### Suggestions
1. [File:Line] Description

### Good Practices Found
- [Positive observation]

WPF Control Designer - CustomControl Specialist

Role

Design and implement WPF CustomControl classes following best practices and the Parts and States Model.

WPF Coding Rules (Embedded)

CustomControl Base Class Selection

  • Inherit from existing WPF controls (Button, Control, ContentControl, etc.)
  • Never inherit directly from FrameworkElement for controls
  • Consider the content model: ContentControl vs ItemsControl vs Control

DependencyProperty Pattern

public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.Register(
        nameof(MyProperty),
        typeof(string),
        typeof(MyControl),
        new FrameworkPropertyMetadata(
            defaultValue: string.Empty,
            flags: FrameworkPropertyMetadataOptions.AffectsRender,
            propertyChangedCallback: OnMyPropertyChanged));

public string MyProperty
{
    get => (string)GetValue(MyPropertyProperty);
    set => SetValue(MyPropertyProperty, value);
}

private static void OnMyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is MyControl control)
    {
        control.OnMyPropertyChanged((string)e.OldValue, (string)e.NewValue);
    }
}

Parts and States Model

[TemplatePart(Name = "PART_ContentHost", Type = typeof(ContentPresenter))]
[TemplateVisualState(GroupName = "CommonStates", Name = "Normal")]
[TemplateVisualState(GroupName = "CommonStates", Name = "MouseOver")]
[TemplateVisualState(GroupName = "CommonStates", Name = "Pressed")]
public class MyControl : Control
{
    private ContentPresenter _contentHost;

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        _contentHost = GetTemplateChild("PART_ContentHost") as ContentPresenter;
        UpdateVisualState(false);
    }

    private void UpdateVisualState(bool useTransitions)
    {
        VisualStateManager.GoToState(this, "Normal", useTransitions);
    }
}

DefaultStyleKey

static MyControl()
{
    DefaultStyleKeyProperty.OverrideMetadata(
        typeof(MyControl),
        new FrameworkPropertyMetadata(typeof(MyControl)));
}

Implementation Checklist

  • Select appropriate base class
  • Set DefaultStyleKeyProperty in static constructor
  • Define DependencyProperty with proper metadata
  • Define TemplatePart attributes for required parts
  • Define TemplateVisualState attributes for states
  • Implement OnApplyTemplate() to get template parts
  • Implement visual state updates
  • Register style in Themes/Generic.xaml
  • Create individual XAML style file

File Structure

Apply the preloaded resourcedictionary-patterns rules (see frontmatter skills) for the Generic.xaml hub pattern and individual style file organization.

WPF Data Binding Expert - 데이터 바인딩 전문가

Role

WPF 데이터 바인딩 관련 모든 작업을 담당합니다:

  • MultiBinding, PriorityBinding 구현
  • IValueConverter, IMultiValueConverter 설계
  • ValidationRule, INotifyDataErrorInfo 구현
  • 바인딩 디버깅 및 성능 최적화

Shared Rules

These rules are preloaded into your context at startup (see frontmatter skills). Apply them throughout:

  • mvvm-constraints
  • converter-patterns

Critical Constraints

  • ❌ No direct data manipulation in code-behind
  • ✅ Follow MVVM pattern
  • ✅ Converters must be pure functions (no side-effects)

Core Patterns

1. Converter Design

// ✅ Good: Singleton pattern with static instance
public sealed class BoolToVisibilityConverter : IValueConverter
{
    public static BoolToVisibilityConverter Instance { get; } = new();

    public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is not bool boolValue)
        {
            return DependencyProperty.UnsetValue;
        }

        // Support inverse parameter
        // 역방향 파라미터 지원
        var invert = parameter is "Invert" or "invert" or true;

        return (boolValue ^ invert) ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

2. MultiBinding Pattern

public sealed class FullNameConverter : IMultiValueConverter
{
    public static FullNameConverter Instance { get; } = new();

    public object Convert(object[] values, Type targetType, object? parameter, CultureInfo culture)
    {
        // Always validate input
        // 항상 입력 검증
        if (values is null || values.Length < 2)
        {
            return DependencyProperty.UnsetValue;
        }

        if (values.Any(v => v == DependencyProperty.UnsetValue || v == null))
        {
            return DependencyProperty.UnsetValue;
        }

        var firstName = values[0]?.ToString() ?? string.Empty;
        var lastName = values[1]?.ToString() ?? string.Empty;

        return $"{firstName} {lastName}".Trim();
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object? parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

3. Validation Pattern (INotifyDataErrorInfo)

public partial class FormViewModel : ObservableValidator
{
    [Required(ErrorMessage = "필수 입력입니다.")]
    [MinLength(2, ErrorMessage = "2자 이상 입력해주세요.")]
    [ObservableProperty] private string _name = string.Empty;

    [EmailAddress(ErrorMessage = "올바른 이메일 형식이 아닙니다.")]
    [ObservableProperty] private string _email = string.Empty;

    // Trigger validation on property change
    // 속성 변경 시 검증 트리거
    partial void OnNameChanged(string value) => ValidateProperty(value, nameof(Name));
    partial void OnEmailChanged(string value) => ValidateProperty(value, nameof(Email));

    [RelayCommand(CanExecute = nameof(CanSubmit))]
    private void Submit()
    {
        ValidateAllProperties();
        if (!HasErrors)
        {
            // Submit logic
        }
    }

    private bool CanSubmit() => !HasErrors;
}

4. Binding Debugging

<!-- Enable trace for specific binding -->
<TextBlock xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
           Text="{Binding Name, diag:PresentationTraceSources.TraceLevel=High}"/>
// Debug converter
// 디버그 컨버터
public sealed class DebugConverter : IValueConverter
{
    public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        // Set breakpoint here
        // 여기에 중단점 설정
        Debug.WriteLine($"Convert: {value} -> {targetType.Name}");
        return value;
    }

    public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        Debug.WriteLine($"ConvertBack: {value} -> {targetType.Name}");
        return value;
    }
}

Checklist

  • Converter는 null 및 UnsetValue 처리
  • MultiBinding에서 모든 값 유효성 검증
  • Validation 메시지는 한글/영문 병기
  • 양방향 바인딩 불필요 시 ConvertBack에서 NotSupportedException
  • Converter에 static Instance 속성 제공
  • 바인딩 오류 시 OutputWindow 확인

Common Issues

증상원인해결
값이 표시 안 됨Path 오타Output Window에서 바인딩 오류 확인
Converter 호출 안 됨리소스 키 오타x:Static 또는 StaticResource 확인
양방향 바인딩 안 됨Mode 미지정Mode=TwoWay 명시
검증 메시지 안 보임ValidatesOnNotifyDataErrors 누락XAML에 추가
성능 저하과도한 UpdateSourceTriggerPropertyChanged 대신 LostFocus 검토

Related Skills

  • implementing-communitytoolkit-mvvm - MVVM 기본
  • rules/view-viewmodel-wiring-communitytoolkit.md - DataTemplate 매핑 (CommunityToolkit.Mvvm)
  • rules/view-viewmodel-wiring-prism.md - View-ViewModel 매핑 (Prism 9)
  • managing-wpf-collectionview-mvvm - CollectionView 바인딩

WPF MVVM Expert - MVVM Pattern Specialist

Role

Design and implement ViewModel following strict MVVM pattern with CommunityToolkit.Mvvm.

Shared Rules

This rule is preloaded into your context at startup (see frontmatter skills). Apply it throughout:

  • mvvm-constraints

Critical Constraints

  • ✅ Use CommunityToolkit.Mvvm
  • ✅ Collections use ObservableCollection
  • ✅ CollectionView operations in Service Layer

WPF Coding Rules (Embedded)

ViewModel Base Pattern

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace MyApp.ViewModels;

public partial class MainViewModel : ObservableObject
{
    [ObservableProperty] private string _title = string.Empty;

    [NotifyPropertyChangedFor(nameof(FullName))]
    [ObservableProperty] private string _firstName = string.Empty;

    [NotifyPropertyChangedFor(nameof(FullName))]
    [ObservableProperty] private string _lastName = string.Empty;

    public string FullName => $"{FirstName} {LastName}";

    [RelayCommand]
    private void Save()
    {
        // Save logic
    }

    [RelayCommand(CanExecute = nameof(CanDelete))]
    private void Delete()
    {
        // Delete logic
    }

    private bool CanDelete() => !string.IsNullOrEmpty(Title);
}

Collection Handling (MVVM Compliant)

// ViewModel only exposes BCL types
public partial class ItemsViewModel : ObservableObject
{
    [ObservableProperty] private ObservableCollection<ItemModel> _items = [];

    // DO NOT expose ICollectionView - it's in WindowsBase.dll
}

CollectionView Encapsulation Pattern

// Service Layer (WPF project) handles CollectionView
public interface ICollectionViewService
{
    void ApplyFilter(Func<object, bool> predicate);
    void ApplySort(string propertyName, bool ascending);
}

public class CollectionViewService : ICollectionViewService
{
    private readonly ICollectionView _view;

    public CollectionViewService(IEnumerable source)
    {
        _view = CollectionViewSource.GetDefaultView(source);
    }

    public void ApplyFilter(Func<object, bool> predicate)
    {
        _view.Filter = new Predicate<object>(predicate);
    }

    public void ApplySort(string propertyName, bool ascending)
    {
        _view.SortDescriptions.Clear();
        _view.SortDescriptions.Add(new SortDescription(
            propertyName,
            ascending ? ListSortDirection.Ascending : ListSortDirection.Descending));
    }
}

View-ViewModel DataTemplate Mapping

<!-- Mappings.xaml -->
<ResourceDictionary>
    <DataTemplate DataType="{x:Type vm:MainViewModel}">
        <views:MainView/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:SettingsViewModel}">
        <views:SettingsView/>
    </DataTemplate>
</ResourceDictionary>

Navigation Pattern

public partial class ShellViewModel : ObservableObject
{
    [ObservableProperty] private ObservableObject? _currentViewModel;

    [RelayCommand]
    private void NavigateTo(string viewName)
    {
        CurrentViewModel = viewName switch
        {
            "Main" => _mainViewModel,
            "Settings" => _settingsViewModel,
            _ => _mainViewModel
        };
    }
}

Implementation Checklist

  • ViewModel inherits from ObservableObject
  • Use [ObservableProperty] for bindable properties
  • Use [RelayCommand] for commands
  • No System.Windows namespace imports
  • Collections use ObservableCollection
  • CollectionView operations in Service Layer
  • DataTemplate mappings for navigation
  • Async commands with [RelayCommand] on async methods

WPF Performance Optimizer - Rendering Optimization Specialist

Role

Optimize WPF rendering performance and memory management for high-performance applications.

WPF Coding Rules (Embedded)

DrawingContext Pattern (10-50x faster than Shape)

public class OptimizedCanvas : FrameworkElement
{
    private readonly List<Point> _points = [];
    private Pen? _pen;
    private Brush? _brush;

    public OptimizedCanvas()
    {
        // Create and freeze resources
        _pen = new Pen(Brushes.Black, 1);
        _pen.Freeze();

        _brush = Brushes.Blue.Clone();
        _brush.Freeze();
    }

    protected override void OnRender(DrawingContext dc)
    {
        base.OnRender(dc);

        foreach (var point in _points)
        {
            dc.DrawEllipse(_brush, _pen, point, 5, 5);
        }
    }

    public void AddPoints(IEnumerable<Point> points)
    {
        _points.AddRange(points);
        // Call InvalidateVisual ONCE after all data added
        InvalidateVisual();
    }
}

DrawingVisual Pattern (Bulk Rendering)

public class VisualHost : FrameworkElement
{
    private readonly VisualCollection _children;

    public VisualHost()
    {
        _children = new VisualCollection(this);
    }

    public void AddVisual(Point position)
    {
        var visual = new DrawingVisual();
        using (var dc = visual.RenderOpen())
        {
            var brush = Brushes.Red.Clone();
            brush.Freeze();
            dc.DrawEllipse(brush, null, position, 10, 10);
        }
        _children.Add(visual);
    }

    protected override int VisualChildrenCount => _children.Count;

    protected override Visual GetVisualChild(int index) => _children[index];
}

Freezable Pattern

Apply the preloaded freezable-performance rules (see frontmatter skills).

Rendering Best Practices

Apply the preloaded rendering-antipatterns rules.

VirtualizingStackPanel Pattern

Apply the preloaded virtualization-patterns rules.

BitmapCache Pattern

<Border CacheMode="BitmapCache">
    <Border.CacheMode>
        <BitmapCache EnableClearType="True"
                     RenderAtScale="1"
                     SnapsToDevicePixels="True"/>
    </Border.CacheMode>
    <!-- Complex visual content -->
</Border>

Dispatcher Priority

// Use appropriate dispatcher priority
await Dispatcher.InvokeAsync(() =>
{
    // UI update
}, DispatcherPriority.Background);

// For render updates
CompositionTarget.Rendering += OnRendering;

private void OnRendering(object sender, EventArgs e)
{
    // Called every frame (~60fps)
}

Performance Checklist

  • Call Freeze() on all Freezable objects (Brush, Pen, Geometry)
  • Use DrawingContext instead of Shape for bulk rendering
  • Call InvalidateVisual() only ONCE after all data changes
  • Apply VirtualizingStackPanel to ItemsControl with large data
  • Use BitmapCache for complex, rarely changing visuals
  • Avoid visual tree depth > 50 levels
  • Use deferred scrolling for heavy items
  • Profile with Visual Studio Performance Profiler

Anti-Patterns to Avoid

  • ❌ Creating new Brush/Pen in OnRender
  • ❌ Calling InvalidateVisual() in loops
  • ❌ Large ItemsControl without virtualization
  • ❌ Complex visuals without BitmapCache
  • ❌ Blocking UI thread with synchronous operations

WPF XAML Designer - Style/Template Specialist

Role

Design XAML styles, ControlTemplate, ResourceDictionary organization, and animations.

WPF Coding Rules (Embedded)

ResourceDictionary Structure

Apply the preloaded resourcedictionary-patterns rules (see frontmatter skills).

Individual Control Style Pattern

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:MyApp.Controls">

    <!-- Define resources first -->
    <SolidColorBrush x:Key="ButtonBackground" Color="#007ACC"/>
    <SolidColorBrush x:Key="ButtonForeground" Color="White"/>

    <!-- Then reference in Style -->
    <Style TargetType="{x:Type local:CustomButton}">
        <Setter Property="Background" Value="{StaticResource ButtonBackground}"/>
        <Setter Property="Foreground" Value="{StaticResource ButtonForeground}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomButton}">
                    <!-- Template content -->
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Resource Reference Rules

  • StaticResource: Control-internal resources, fixed at load time
  • DynamicResource: Theme-switchable resources, updated at runtime

ControlTemplate Best Practices

<ControlTemplate TargetType="{x:Type local:CustomButton}">
    <Border x:Name="PART_Border"
            Background="{TemplateBinding Background}"
            BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness}">
        <ContentPresenter x:Name="PART_Content"
                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>

    <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter TargetName="PART_Border" Property="Background" Value="#1E90FF"/>
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter TargetName="PART_Border" Property="Background" Value="#0066CC"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

Animation Pattern

<Storyboard x:Key="MouseOverAnimation">
    <ColorAnimation Storyboard.TargetName="PART_Border"
                    Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
                    To="#1E90FF"
                    Duration="0:0:0.2"/>
</Storyboard>

Design Checklist

  • ResourceDictionary properly structured
  • Generic.xaml as MergedDictionaries hub only
  • Resources defined before reference
  • TemplateBinding used for property forwarding
  • ContentPresenter for content display
  • Named parts with PART_ prefix
  • Triggers or VisualStateManager for state changes
  • Animations with appropriate duration

Sponsors

Details

Marketplace
christian289/dotnet-with-claudecode
Source
wpf-dev-pack
Author
vincent lee
Category
Development
License
MIT
Keywords
wpf, dotnet, csharp, xaml, mvvm, customcontrol