Skip to content

Resolve ThemeRef through WinUI instead of reading theme dictionaries - #1633

Merged
Alexandre Zollinger Chohfi (azchohfi) merged 9 commits into
mainfrom
azchohfi-fix-themeref-resolve-nonactive-theme
Nov 20, 2026
Merged

Alexandre Zollinger Chohfi (azchohfi) merged 9 commits into
mainfrom
azchohfi-fix-themeref-resolve-nonactive-theme

Conversation

@azchohfi

@azchohfi Alexandre Zollinger Chohfi (azchohfi) commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

ThemeRef.Resolve read WinUI's theme dictionaries from code. WinUI creates a theme dictionary entry the first time it is read and resolves it for the app's theme, then keeps it for every element. So in a Light app, resolving the Dark brush returned the Light color, and every Dark element using that key showed the Light color from then on. In a sweep of 40 common keys, 32 were affected, in both directions. Setting RequestedTheme on the window root doesn't help, only the app theme counts.

The same lookup backed .Resources(...) overrides with theme tokens under an element with the other RequestedTheme, and validation styling in such a subtree.

Reactor now asks WinUI to resolve {ThemeResource key} on an off-tree Border with the requested RequestedTheme and reads the value back (ThemeResourceProbe). This gets the same brush an element in that theme gets, without touching WinUI's shared entries. Only when WinUI can't resolve the key for that theme does it fall back to the old dictionary walk, for example for an app key defined only in Dark, or only in Default next to Light and Dark. The walk skips XamlControlsResources, including when it is Application.Resources itself as in every Reactor app, so it can never read WinUI's own entries from code. Missing and non-brush keys still return null, and the (key, theme) brush cache is unchanged.

The probe parses a small Style with XamlReader, cached per key and UI thread, the same mechanism ApplyThemeBindings already uses. Stable WinUI has no code API for a {ThemeResource} reference. FrameworkElement.SetThemeResourceBinding (microsoft/microsoft-ui-xaml#11229) is that API, and I checked it on 2.6.6-experimental. It returns the right brush for all 40 keys in both app themes and doesn't change the shared entries, so it can replace the Style once it's stable. #1634 tracks that move.

Linked issue / spec

Fixes #1534

Related: #1531 (spec 065 §7 describes this bug, and it rewrites the same ResolveForThemeUncached for contrast themes, #1506), #1618 (moves ApplyThemeBindings to SetThemeResourceBinding), #1634 (follow-up move of this probe to the same API).

Test plan

  • Fresh-process regression test. The bug only shows when a key is first read in a clean process, so the test host has a --themeref-probe <scenario> mode, driven by ThemeRefProbeProcessTests in tests/Reactor.SelfTests. It does one first read for the theme opposite to the app's, then renders Theme.Ref borders in both themes.
    • Scenarios cover ThemeRef.Resolve(key, isDark), Resolve(key, fe) (the validation path), .Resources overrides, a missing key, and the dictionary-walk fallback run on its own for real keys.
    • A positive control does no read. A negative control does the old dictionary read and checks that it still makes the other-theme border show the app theme's brush.
    • The three read scenarios failed on the unfixed code and pass now. The fallback-walk scenario fails when the XamlControlsResources guard is removed and passes with it. All 7 tests pass, locally and in CI.
    • In a Windows contrast theme, Light and Dark share brushes, so the probe reports a skip and the tests are Inconclusive rather than failing.
  • Selftest fixtures in ThemeRefResolutionFixtures.cs.
    • Resolved brushes match a live {ThemeResource} border in both themes.
    • Keys with odd characters resolve.
    • Partial-theme keys still resolve through the fallback, including a cached style applied for a theme without the key.
    • Missing or non-brush keys return null.
  • Unit tests in ThemeResourceProbeTests.cs for the markup quoting and XML escaping, and for keys that go straight to the fallback (control characters, tab/CR/LF, lone surrogates).
  • Mutation check. Ignoring the requested theme, dropping the fallback, dropping the quoting, and dropping the XamlControlsResources guard each failed the intended tests.
  • dotnet test tests/Reactor.Tests passed, 15,955 tests.
  • dotnet test tests/Reactor.SelfTests on an interactive desktop: 2,098 passed. The 3 failures were two CommandBarFlyout open-timing fixtures and a shutdown probe timeout. All three pass alone, and the flyout fixtures fail the same way on main.
  • dotnet test tests/Reactor.PackagedTests -p:Platform=x64: 2,089 passed. The 3 failures were the same two flyout fixtures and WindowLevel_RuntimeFlip_Topmost, which also fails 2 out of 3 times on main.
  • HostThemeChangeTests E2E passed.
  • After the review fixes I reran the Theme_, CoreCov_ThemeRef, Item1, Issue675, ResourceOverride, ThemeBindings, FlyoutTarget_Memo, Validation, FormField and NotifyResources selftests, the 7 process tests, and the theme unit tests. All passed.
  • Release builds of src/Reactor and the test projects with warnings as errors locally. The full Reactor.slnx Release build ran in CI, along with selftests, packaged and AOT selftests, and passed.
  • Not checked under a Windows contrast theme.

Risk / breaking changes

  • No public API change.
  • ThemeRef.Resolve and .Resources(...) theme overrides now return the correct brush for the theme the app isn't using, which is what the API always promised.
  • Resolution goes through WinUI's {ThemeResource} lookup. Where an app defines the same key in more than one merged dictionary, WinUI's lookup order now decides which one wins, the same as {ThemeResource}. While a Windows contrast theme is on, the result should follow WinUI too, but I haven't checked it by hand.
  • A key that exists nowhere costs a failed XAML parse plus the dictionary walk on each resolve, roughly 1.5 ms. Failed lookups aren't cached, so a dictionary merged later still resolves without Theme.NotifyResourcesChanged(). Avoid resolving a missing key per cell.
  • The Devtools resources tool also reads every theme dictionary entry and has the same side effect. That's out of scope here.

…1534)

Reading a WinUI theme dictionary entry from code creates it for the
application theme and shares it app-wide, so resolving the other theme
returned the wrong brush and changed it for every element. ThemeRef now
asks WinUI to resolve {ThemeResource key} on an off-tree element with the
requested RequestedTheme, and falls back to the dictionary walk only for
keys WinUI cannot resolve for that theme.

Adds a fresh-process probe (--themeref-probe) with MSTest coverage for
ThemeRef.Resolve, the element overload and .Resources overrides, plus
selftest fixtures and unit tests for the probe.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…n coverage

- Update the theming-tokens guide and the design-docs skill, which still described
  ThemeRef resolution as a ThemeDictionaries walk.
- Add a raw-read negative control and a missing-key scenario to the fresh-process probe.
- Send keys XML can't hold as written (control characters, tab/CR/LF, lone surrogates)
  to the dictionary walk instead of the probe.
- Cover a cached probe style applied for a theme that lacks the key.
- State the contrast-theme behavior as a property of the lookup.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…ghten tests and docs

- The dictionary-walk fallback skips XamlControlsResources, so it can never read WinUI's
  own theme entries from code.
- Document the fallback's plain-lookup step on ThemeRef.Resolve; drop the untested
  contrast-theme claim.
- Docs: ThemeRef.Resolve resolves for the theme passed as isDark, not the element's theme.
- Replace XmlConvert with an in-file XML Char check so trimmed apps don't keep System.Xml.
- The raw-read negative control asserts the poisoning itself; the app-only-key fixture
  asserts the actual brush.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…-resolve-nonactive-theme

# Conflicts:
#	CHANGELOG.md

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The theme probes incorrectly report regressions under Windows high-contrast themes because Light and Dark can legitimately share system brushes, requiring explicit skip handling and a guarded distinctness assertion.

1 open issue
What changed in this PR

Fixes #1534 by letting WinUI resolve ThemeRef brushes for the requested theme, avoiding dictionary reads that could return the wrong color and affect other elements. The change also benefits theme-backed resource overrides and validation styling without changing the public API.

Changes:

  • Adds an off-tree resource probe with cached Styles, retaining a dictionary fallback for unresolved app keys.
  • Adds fresh-process regression controls, live theme-resolution fixtures, and markup-escaping unit tests.
  • Updates documentation and the changelog to explain the resolution behavior.
File Description
tests/​Reactor.Tests/​ThemeResourceProbeTests.cs Tests key quoting, XML escaping, and unsupported characters.
tests/​Reactor.SelfTests/​ThemeRefProbeProcessTests.cs Runs isolated regression scenarios with positive and negative controls.
tests/​Reactor.AppTests.Host/​ThemeRefProbe.cs Implements fresh-process reads and themed-border comparisons.
tests/​Reactor.AppTests.Host/​SelfTest/​SelfTestFixtureRegistry.cs Registers four resolution fixtures.
tests/​Reactor.AppTests.Host/​SelfTest/​Fixtures/​ThemeRefResolutionFixtures.cs Covers theme matching, unusual keys, fallback, and null results.
tests/​Reactor.AppTests.Host/​Program.cs Adds the dedicated probe entry point.
src/​Reactor/​Core/​ThemeResourceProbe.cs Resolves resources through a themed Border and cached XAML Style.
src/​Reactor/​Core/​Theme.cs Uses the probe before fallback and excludes explicit traversal into WinUI dictionaries.
skills/​design-docs/​theme-aware-resources.md Explains native resolution and unsafe dictionary reads.
docs/​guide/​theming-tokens.md Updates the generated resolution guide.
docs/​guide/​reactor-vs-xaml.md Updates the generated ThemeRef comparison and source excerpt.
docs/​_pipeline/​templates/​theming-tokens.md.dt Updates the source template for resolution guidance.
docs/​_pipeline/​templates/​reactor-vs-xaml.md.dt Updates the source template for the XAML comparison.
CHANGELOG.md Records the cross-theme brush fix and affected callers.

Review effort: Balanced

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build metrics

Artifact sizes for 38197d5 vs the base branch (9569c46).

Packages (compressed .nupkg)

Artifact base PR Δ
Microsoft.UI.Reactor.nupkg 2.09 MB 2.09 MB +1.76 KB (+0.08%) ⚠️
Microsoft.UI.Reactor.Advanced.nupkg 528.6 KB 528.6 KB -11 B (0.00%) ≈
Microsoft.UI.Reactor.Devtools.nupkg 287.9 KB 287.8 KB -17 B (-0.01%) ≈

Assemblies in Microsoft.UI.Reactor

Artifact base PR Δ
Reactor.Analyzers.dll 422.5 KB 422.5 KB +0 B (0.00%) ≈
Reactor.dll 2.83 MB 2.83 MB +1.50 KB (+0.05%) ⚠️
Reactor.Localization.Generator.dll 16.0 KB 16.0 KB +0 B (0.00%) ≈
Reactor.Wrappers.Abstractions.dll 10.5 KB 10.5 KB +0 B (0.00%) ≈
Reactor.Wrappers.Generator.dll 164.0 KB 164.0 KB +0 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor.Advanced

Artifact base PR Δ
Reactor.Advanced.dll 1.08 MB 1.08 MB +0 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor.Devtools

Artifact base PR Δ
Microsoft.UI.Reactor.Devtools.dll 787.0 KB 787.0 KB +0 B (0.00%) ≈

✅ smaller / ⚠️ larger / ≈ within noise. Sizes come from a Release dotnet pack on the CI runner: packages are the compressed .nupkg download size, assemblies the uncompressed DLL inside it.
workflow run.

- The fresh-process probe reports a skip in a Windows contrast theme, where Light and Dark
  share brushes, and the MSTest driver maps it to Inconclusive; the fixture skips only its
  distinctness check there.
- Drop the generic catch in the app-only-key fixture check.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The guard misses root-level XamlControlsResources, allowing fallback lookup to enter native theme dictionaries and bypass protection against issue #1534 in normal Reactor apps.

1 open issue
1 resolved since last review

Review effort: Balanced

Comment thread src/Reactor/Core/Theme.cs Resolved
@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

🧪 Merged coverage

Coverage for 38197d5 vs the base branch (9569c46) — unit + selftest merged.

Metric base PR Δ
Line 88.69% 88.69% 0.00 pp ≈
Branch 45.73% (18375/40179) 45.73% (18382/40199) 0.00 pp ≈

No coverage change beyond the noise floor. ✅

✅ higher / ⚠️ lower / ≈ within noise. Δ is in percentage points; coverage is unit + selftest merged (Debug x64) on the CI runner. Cobertura reports attached to the workflow run as artifacts.

The dictionary-walk fallback skips XamlControlsResources' own theme dictionaries when it is
Application.Resources itself, as in every Reactor app, not only when it is merged. A new
fresh-process scenario runs the fallback walk alone on real keys for the other theme and
checks that WinUI's entries stay correct.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The fallback skips app dictionaries nested beneath merged XamlControlsResources, causing partial-theme resources such as a Dark-only brush in a Light app to resolve to null.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Recurse into nested XamlControlsResources for theme fallback

src/​Reactor/​Core/​Theme.cs:232

When an app dictionary is nested beneath a merged XamlControlsResources, this continue makes its partial-theme keys unreachable by the fallback. A Dark-only brush in a Light app then resolves to null: the probe cannot load the reference, and the final plain lookup uses Light. Recurse through this node instead—the current-dictionary guard above already protects WinUI's own theme entries—and add a regression case for this nested shape.

1 resolved since last review

Review effort: Balanced

@azchohfi Alexandre Zollinger Chohfi (azchohfi) added ready-for-review Agent work and technical checks complete; awaiting review, not approval or merge and removed agent-preparing Agent is addressing feedback or completing required validation and CI labels Nov 20, 2026
Keeps both CHANGELOG Fixed entries. ThemeResourceProbe now builds its markup with
Reconciler.FormatThemeResourceReference, which #1636 added with the same quoting and
escaping rules, instead of its own copy.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@azchohfi Alexandre Zollinger Chohfi (azchohfi) added agent-preparing Agent is addressing feedback or completing required validation and CI and removed ready-for-review Agent work and technical checks complete; awaiting review, not approval or merge labels Nov 20, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Skipping merged XamlControlsResources also bypasses app-owned dictionaries, causing previously resolvable brushes defined only for the opposite theme to return null.

1 open issue

Review effort: Balanced

Comment thread src/Reactor/Core/Theme.cs Resolved
…trolsResources

The per-dictionary guard already keeps the fallback out of WinUI's own theme entries, so
recursing into a merged XamlControlsResources is safe and reaches app dictionaries merged
into it, as it already did for the root.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues remain for the cross-theme ThemeRef resolution change.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@azchohfi Alexandre Zollinger Chohfi (azchohfi) added ready-for-review Agent work and technical checks complete; awaiting review, not approval or merge and removed agent-preparing Agent is addressing feedback or completing required validation and CI labels Nov 20, 2026
@azchohfi
Alexandre Zollinger Chohfi (azchohfi) merged commit 1265b86 into main Nov 20, 2026
46 checks passed
@azchohfi
Alexandre Zollinger Chohfi (azchohfi) deleted the azchohfi-fix-themeref-resolve-nonactive-theme branch November 20, 2026 22:58
@azchohfi Alexandre Zollinger Chohfi (azchohfi) removed the ready-for-review Agent work and technical checks complete; awaiting review, not approval or merge label Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] ThemeRef.Resolve for a theme the app isn't using returns the wrong color and changes the brush for the whole app

2 participants