Skip to content

Resolve theme references from the HighContrast dictionary in contrast themes - #1509

Draft
Niels Laute (niels9001) wants to merge 7 commits into
mainfrom
niels9001-theme-high-contrast
Draft

Niels Laute (niels9001) wants to merge 7 commits into
mainfrom
niels9001-theme-high-contrast

Conversation

@niels9001

@niels9001 Niels Laute (niels9001) commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

While a Windows contrast theme was on, brushes that Reactor resolves itself kept their light or dark colors: .Resources(...) theme overrides, ThemeRef.Resolve(...), and Reactor's own validation styling. The resolver only looked at the Light, Dark and Default theme dictionaries.

Theme.* modifiers such as .Background(Theme.CardBackground), and Card(), were not affected. They are applied as native {ThemeResource} style setters, and WinUI already resolves those for contrast themes.

One WinUI behavior shapes the fix. WinUI creates a theme dictionary entry the first time something reads it, and resolves the references inside it for the theme WinUI uses at that moment. Then it keeps that entry for every element in the app. So when code reads a dictionary for another theme, that entry gets the wrong values, for the whole app. For example, the Light entry of CardBackgroundFillColorDefaultBrush, read while WinUI is in a contrast theme, gets the HighContrast dictionary's #FF0000 and stays red (see Screenshots).

What changes:

  • Resolution. While WinUI is in a contrast theme, ThemeRef resolution reads only the HighContrast theme dictionaries, whatever isDark asks for.
    • A key without a contrast value resolves to nothing, and the control keeps its own contrast colors. The first version of this PR fell back to the Light, Dark or Default dictionary there, which could create those entries with contrast values. That fallback is gone.
    • The plain-resource fallback is skipped during a contrast theme too, because WinUI's ResourceDictionary.TryGetValue also reads the theme dictionaries of the theme it uses (a selftest pins this).
    • In WinUI 2.2.1, the Light, Default and HighContrast dictionaries define the same 2,683 keys. So every Theme.* token and the validation brush have a contrast value, and only app-defined keys can resolve to nothing.
  • When to switch. Reactor follows the contrast state that WinUI has applied, not the system setting. Windows announces a switch (WM_SETTINGCHANGE, UISettings.ColorValuesChanged, SPI_GETHIGHCONTRAST) before WinUI applies it. The first version of this PR refreshed on WM_SETTINGCHANGE and read the dictionaries in that gap: in an app that started with a contrast theme on, overrides turned red when it was turned off.
    • Each host merges a small theme probe into its content root: one color per theme dictionary, and a brush with a {ThemeResource} reference to that color. This covers ReactorHost (so ReactorWindow and raw-window hosts) and ReactorHostControl. WinUI updates the reference itself when it applies a theme. The probe then reports, on a later dispatcher turn, whether WinUI is in a contrast theme.
    • A probe counts and reports only while its root is in the live tree, because WinUI updates nothing else. With no probe in the tree, the system setting stands in. The hosts ask their probe to check again when they are loaded or unloaded, or when their content changes. A probe on a new content root takes over at once from a live one, so a root swap doesn't fall back to the system setting for a moment.
    • When the reported state changes, Theme.NotifyResourcesChanged() re-renders every host, memoized subtrees included. Every host reports the same switch. Only the first report refreshes, and a first report before anything was resolved refreshes nothing.
    • Until a probe reports (no host has content yet), the system setting stands in: SystemParametersInfo(SPI_GETHIGHCONTRAST), cached and read again on every resolution-cache invalidation.
    • The WM_SETTINGCHANGE hooks of the first version are removed.
  • Docs. CHANGELOG entry under Fixed, and the high-contrast section of skills/design-docs/theme-aware-resources.md.

Screenshots

A light-theme app with three buttons: a built-in button, .Background(Theme.CardBackground), and a .Resources(...) override of ButtonBackground with Theme.CardBackground. The same code is built from main (6889229) and from this PR (500ca22), with the Aquatic contrast theme. Each window shows its client area only.

main This PR
Contrast turned on while the app runs main, contrast turned on while the app runs: the built-in and .Background buttons use contrast colors, the .Resources override is a light gray block This PR, contrast turned on while the app runs: all three buttons use contrast colors
App started with contrast already on main, app started with contrast on: the .Resources override is bright red This PR, app started with contrast on: all three buttons use contrast colors
Contrast turned off again: the app from row 1 main, contrast off again for the app from row 1: all three buttons are light This PR, contrast off again for the app from row 1: all three buttons are light
Contrast turned off again: the app from row 2 main, contrast off again for the app from row 2: the .Background and .Resources buttons are bright red This PR, contrast off again for the app from row 2: all three buttons are light

Row 4 on main: the .Background(...) modifier is red as well. At startup, main read the Light entry of the card brush while WinUI was in the contrast theme, and WinUI keeps that entry for the whole app. With this PR, all three buttons follow every switch.

Linked issue / spec

Fixes #1506. This unblocks the high-contrast item of #1505 (SettingsCard and SettingsExpander).

Test plan

  • Unit tests in tests/Reactor.Tests/HighContrastThemeTests.cs:
    • a switch that Windows announced is not used until WinUI has applied it, both ways;
    • each switch refreshes the hosts once; a second host's report doesn't refresh again, and a first report before anything was resolved refreshes nothing;
    • the system setting stands in until a probe reports, is read again after a cache invalidation, and stands in again when the last probe goes;
    • the real SystemParametersInfo call succeeds and agrees with AccessibilitySettings.HighContrast.
  • Selftests in tests/Reactor.AppTests.Host/SelfTest/Fixtures/HighContrastThemeFixtures.cs, 30 checks. Test seams play the contrast state, the setting Windows announces and what a probe reads, so the tests don't change the desktop.
    • ThemeRef.Resolve reads only the HighContrast dictionary for light and dark requests, a key without a contrast value resolves to nothing, and the Fluent CardBackgroundFillColorDefaultBrush resolves to its contrast brush. WinUI's plain TryGetValue reads the theme dictionaries, which is why the plain fallback is skipped.
    • WinUI itself updates the probe on a real Light/Dark switch, the same kind of theme update as a contrast switch. The probe follows a new content root, and a replacement counts at once. It counts only while it is in the live tree, goes with empty content, and goes away with the host. A raw host's content root still raises Loaded (see the CI finding below).
    • A .Resources(...) override keeps its colors when Windows announces a switch, and switches when a ReactorWindow's probe reports that WinUI applied it, both ways. The same for a raw-window ReactorHost, and for an embedded ReactorHostControl including a Memo subtree. Negative control: a partial re-render leaves the memoized override stale.
  • Mutation checks, each failing exactly the expected checks:
    • contrast state taken from the system setting again: 4 unit tests and 4 selftest checks fail (HC_Window_AnnouncedSwitchWaitsForWinUI, HC_Window_AnnouncedOffWaitsForWinUI, HC_RawHost_AppliedSwitchUsesContrast, HC_HostControl_MemoUsesContrast);
    • the first version's contrast-time fallback restored: HC_On_KeyWithoutContrastValueResolvesNothing fails;
    • a probe that counts off the live tree, and one kept on empty content: HC_Probe_CountsOnlyInTheLiveTree and HC_Probe_GoesWithEmptyContent fail;
    • no new liveness check when the host is unloaded: HC_Probe_CountsOnlyInTheLiveTree fails;
    • no takeover on a root swap: HC_Probe_ReplacementCountsAtOnce fails;
    • the probe subscribed to its root's Loaded again: HC_RawHost_RootStillLoads fails.
  • dotnet test tests/Reactor.Tests: passed (15,729 passed, 18 skipped, 0 failed).
  • dotnet run --project tests/Reactor.AppTests.Host -- --self-test --filter "Theme_": 0 failures (158 checks).
  • Release builds of src/Reactor, tests/Reactor.Tests and tests/Reactor.AppTests.Host: 0 errors, 0 compiler warnings. For tests/Reactor.Tests the restore ran on its own, as in CI; a one-shot -c Release build on this machine turns the proxied feed's NU1902/NU1903 package-audit warnings into errors. I did not run the full Reactor.slnx Release build locally.
  • Code review of the probe version by a code-review agent, in two rounds: two medium findings, both fixed.
    • A probe kept counting after its root left the live tree, so its last report could pin a stale state. Fixed in 2bf45b9.
    • On a root swap, the count passed through zero, so the system setting stood in for a moment. Fixed in ee3d11f: the new probe takes over from a live one.
  • CI found a regression in ee3d11f. The probe subscribed to its root's Loaded and Unloaded, and subscribing while the root enters the tree during a render stopped WinUI from raising Loaded for that root (A11y_FocusTrap_ContainerIsMountedFE failed). Fixed in 500ca22: the probe subscribes to no root events, and the hosts ask it to check again instead.
  • CI at 500ca22: all checks pass.
  • pr-review skill, run once on the first version:
    • primary review by two Claude reviewers, cross-family check by gpt-6.1-sol;
    • 0 critical, 0 high, 4 medium, 1 low; the cross-family check confirmed the 4 medium findings and disputed the low one;
    • all of them were addressed in the second commit.
  • By hand: while a Reactor app with .Resources(...) theme overrides is open, turn a contrast theme on and off (Settings > Accessibility > Contrast themes) and check that the overrides switch (checked with the demo in Screenshots, switching the contrast theme with SystemParametersInfo(SPI_SETHIGHCONTRAST)).

Risk / breaking changes

  • No public API change.
  • ThemeRef.Resolve(key, isDark) returns the contrast brush while a contrast theme is on, as {ThemeResource} does. For a key without a contrast value it returns null during a contrast theme; on main it returns the light or dark brush. All built-in Theme.* tokens have contrast values.
  • Each host merges one small resource dictionary (keys ReactorThemeProbeColor and ReactorThemeProbeBrush) into its content root's resources, and moves it when the root changes. The probe subscribes to no events of the root: subscribing to a root's Loaded while it enters the tree during a render stops WinUI from raising Loaded for that root.
  • The per-resolve cost is a cached flag read, so the hot path stays a dictionary hit.
  • A contrast switch triggers one full re-render per host, after WinUI has applied it.

… themes

Reactor resolved ThemeRef brushes only from the Light/Dark/Default theme
dictionaries, so `.Resources(...)` theme overrides, `ThemeRef.Resolve(...)`
and Reactor's own resolved brushes kept their Light/Dark colors while a
Windows contrast theme was on. `Theme.*` modifiers were not affected: they
use native {ThemeResource} setters.

- ThemeRef resolution tries the "HighContrast" theme dictionary first while
  a contrast theme is on, then falls back as before. The contrast setting is
  read with SystemParametersInfo(SPI_GETHIGHCONTRAST) (no WinRT activation),
  cached, re-read on every cache invalidation, and part of the cache key.
- ReactorWindow handles WM_SETTINGCHANGE / SPI_SETHIGHCONTRAST: when the
  setting moved, Theme.NotifyResourcesChanged() refreshes every host. The
  window host only listened to UISettings.ColorValuesChanged after a chart
  had started. The existing ColorValuesChanged handlers use the same check.
- Tests: unit tests for the re-read and the one-refresh-per-change rule;
  selftests for HighContrast-dictionary resolution (with fallback) and for a
  `.Resources(...)` override following a WM_SETTINGCHANGE.

Fixes #1506

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

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build metrics

Artifact sizes for 500ca22 vs the base branch (6889229).

Packages (compressed .nupkg)

Artifact base PR Δ
Microsoft.UI.Reactor.nupkg 2.05 MB 2.06 MB +5.74 KB (+0.27%) ⚠️
Microsoft.UI.Reactor.Advanced.nupkg 521.7 KB 521.7 KB -5 B (0.00%) ≈
Microsoft.UI.Reactor.Devtools.nupkg 287.9 KB 287.9 KB +7 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor

Artifact base PR Δ
Reactor.Analyzers.dll 411.0 KB 411.0 KB +0 B (0.00%) ≈
Reactor.dll 2.79 MB 2.79 MB +10.0 KB (+0.35%) ⚠️
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 145.5 KB 145.5 KB +0 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor.Advanced

Artifact base PR Δ
Reactor.Advanced.dll 1.06 MB 1.06 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 Fluent tokens themselves: XamlControlsResources ships a HighContrast dictionary.
var fluentContrast = ThemeRef.Resolve("CardBackgroundFillColorDefaultBrush", isDark: false);
H.Check("HC_On_FluentTokenUsesContrastBrush",
fluentLight is not null && fluentContrast is not null && !ReferenceEquals(fluentLight, fluentContrast),
@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🧪 Merged coverage

Coverage for 500ca22 vs the base branch (6889229) — unit + selftest merged.

Metric base PR Δ
Line 88.59% 88.60% +0.01 pp ≈
Branch 46.38% (18059/38935) 46.30% (18083/39059) -0.08 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.

…nippet

- A ReactorHost over a raw Window (tray flyout, app-built Window) has no
  ReactorWindow message monitor; it now watches WM_SETTINGCHANGE itself.
  New hosts read the contrast setting again instead of trusting a value
  cached for an earlier window.
- The refresh dedupe tracks the setting the hosts were last fully refreshed
  for, not the last value any resolve saw: a partial re-render that already
  resolved with the new setting no longer suppresses the full refresh that
  memoized subtrees need.
- HighContrastState.TryReadSystem makes a failing system call observable; a
  unit test checks it succeeds and agrees with AccessibilitySettings.
- Selftests: the setting-change fixture no longer depends on the app theme
  and sends literal message values; new fixtures cover the raw-host monitor
  and an embedded ReactorHostControl refreshing a memoized subtree on
  ColorValuesChanged (with a negative control).
- Move the new XML-doc sentence out of the theme-ref snippet region, so the
  compiled docs/guide/reactor-vs-xaml.md does not change.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Application.Current.Resources.MergedDictionaries.Remove(dict);
RestoreSystemSetting();
H.SetContent(null);
try { window.Close(); } catch (global::System.Runtime.InteropServices.COMException) { }
Resolve the CHANGELOG.md conflict: keep both [Unreleased] Fixed entries, ordered
by issue number (#1268 from main, then #1506).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The first version re-resolved theme references on WM_SETTINGCHANGE, before
WinUI had applied the contrast switch, and fell back to the Light, Dark and
Default dictionaries for keys without a contrast value. WinUI creates a theme
dictionary entry on its first read and resolves it for the theme it uses at
that moment, then keeps it for every element. Both paths could therefore fix
entries to the wrong theme's values: after a contrast theme was turned off in
an app that started with it, the overrides stayed red (#FF0000).

- Each host merges a small theme probe into its content root: a brush with a
  {ThemeResource} reference that WinUI updates itself when it applies a
  theme. HighContrastState follows what the probes report, so resolution and
  the refresh happen after WinUI has switched. The system setting only stands
  in until a probe has reported. The WM_SETTINGCHANGE hooks are removed.
- While WinUI is in a contrast theme, resolution reads only the HighContrast
  dictionaries, and a key without a contrast value resolves to nothing. The
  plain TryGetValue fallback is skipped then too, because it reads the theme
  dictionaries of the theme WinUI uses.
- Unit tests and selftests for the new state, the probe and the resolver;
  CHANGELOG and the high-contrast design note updated.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
if (dictionary is not null)
{
try { resources?.MergedDictionaries.Remove(dictionary); }
catch (global::System.Runtime.InteropServices.COMException) { }
Comment thread src/Reactor/Hosting/ThemeProbe.cs Fixed
Review finding: a probe kept counting after its root left the live tree
(empty content in ReactorHostControl, the built-in error panel, an unloaded
or dropped host). WinUI no longer updates such a probe, so its last report
kept HighContrastState on a stale value, and the next first-time dictionary
reads could fix entries to the wrong theme.

- A probe counts and reports only while its root is in the live tree. It is
  live on Loaded, and a tree check on a later turn decides at attach and
  after Unloaded: a raw host's root never gets Loaded, and its IsLoaded stays
  false. With no probe in the tree, the system setting stands in again.
- ReactorHostControl drops the probe when its content becomes empty, and
  both hosts attach a new probe only when the root changes.
- Selftests for both cases; the probe fixture checks each probe's own state,
  because other fixtures' probes come and go on later turns.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
{
public override async Task RunAsync()
{
var host = new ReactorHostControl();
_owner.Unloaded -= OnOwnerUnloaded;
_brush.UnregisterPropertyChangedCallback(SolidColorBrush.ColorProperty, _token);
try { _owner.Resources?.MergedDictionaries.Remove(_dictionary); }
catch (global::System.Runtime.InteropServices.COMException) { }
Review finding on the previous commit: when a host swapped its root, the
new probe counted only after its deferred tree check, but the old one was
disposed at once. In a single-host app the count passed through zero, and
the system setting stood in for that moment. That is exactly when it can be
ahead of WinUI: a root that depends on the contrast setting swaps when
Windows announces the switch. Reads of the HighContrast dictionary in that
gap could fix its entries to light values.

A probe that replaces a live one now counts at once. Its tree check still
withdraws it if the new root is off the tree. New selftest check.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Niels Laute (niels9001) added a commit that referenced this pull request Nov 16, 2026
Brings the #1509 fix that follows contrast switches once WinUI applies them.

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

# Conflicts:
#	tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs
Niels Laute (niels9001) added a commit that referenced this pull request Nov 16, 2026
Brings the #1509 follow-up: a theme probe counts only while its root is in the live tree.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Niels Laute (niels9001) added a commit that referenced this pull request Nov 16, 2026
Brings the #1509 follow-up: a live theme probe hands over on a root swap.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CI found that a raw host's root no longer loaded
(A11y_FocusTrap_ContainerIsMountedFE). The probe subscribed to the root's
Loaded and Unloaded events while the root entered the tree during a render,
and that stops WinUI from raising Loaded for it at all, so IsLoaded stayed
false and the app's own Loaded handlers on the root would never run.

- The probe no longer subscribes to the root's events. It checks the tree
  itself on a later turn: at attach, and when its host says the tree may
  have changed (ReactorHostControl's own Loaded and Unloaded, and the
  built-in error panel taking the content's place).
- Selftests: HC_RawHost_RootStillLoads pins the regression; the probe
  fixture polls for the live state, which a slow runner reaches later than
  one render.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Niels Laute (niels9001) added a commit that referenced this pull request Nov 16, 2026
Brings the #1509 fix that keeps the theme probe off the root's Loaded and Unloaded events.

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

This branch has not been deployed

No deployments
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] .Resources(...) theme overrides and ThemeRef.Resolve ignore high contrast

1 participant