Skip to content

Bind ThemeRef properties with SetThemeResourceBinding instead of a parsed Style - #1618

Draft
Alexandre Zollinger Chohfi (azchohfi) wants to merge 1 commit into
azchohfi-winui3-integration-datatemplatefrom
azchohfi-set-theme-resource-binding
Draft

Alexandre Zollinger Chohfi (azchohfi) wants to merge 1 commit into
azchohfi-winui3-integration-datatemplatefrom
azchohfi-set-theme-resource-binding

Conversation

@azchohfi

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

Copy link
Copy Markdown
Collaborator

Summary

ThemeRef modifiers (.Background(Theme.X), .Foreground(...), .BorderBrush(...), .WithBorder(...), SplitView.PaneBackground(...)) now bind each property with FrameworkElement.SetThemeResourceBinding, the code equivalent of {ThemeResource}. On main, Reconciler.ApplyThemeBindings builds a <Style> with {ThemeResource} setters as a XAML string, parses it with XamlReader.Load, caches it and assigns fe.Style, built BasedOn the app's own Style since #1636.

This stacks on #1125 and can't merge before it. SetThemeResourceBinding is an experimental WinUI API (spec microsoft/microsoft-ui-xaml#11229). It only exists on the 2.6.6-experimental channel that #1125 moves to, so this PR inherits the same limitation and graduation gate, and is expected to be stable in 2.7.2. The projection doesn't mark the member [Experimental], so the call doesn't raise CS8305 and no pragma was needed.

#1636 already shipped the user-visible fixes from this work on the stable SDK, through the Style path. Those are the SplitView.PaneBackground(ThemeRef) mapping, InteractionStates no longer freezing a ThemeRef, the app's Style kept as BasedOn, and quoted keys. This PR keeps every one of those behaviors and swaps the mechanism underneath.

What changes

  • ApplyThemeBindings binds each mapped property and keeps a record on the control's ReactorState. The record holds the key, the brush Reactor installed, and whether a brush modifier is currently suppressing it. It lives on the native control, so it survives a collected managed wrapper. The public ApplyThemeBindings(fe, bindings) signature is kept.
  • When an element drops some of its ThemeRefs, Update clears just those before the element's setters run. The element pool clears every binding on return ([Bug] TextBlocks styling returned from the different states of UseResource will overlap. #522). Only properties Reactor bound are touched.
  • Removed, because no Style is written any more. The themed-Style caches, the ReactorAppliedThemeStyle ownership marker, BuildCacheKey and ClearStyleCache, the BasedOn base-style id stamping and the incompatible-base fallback, the DefaultSplitViewStyle workaround for loaded SplitViews, and the warning for keys that can't be written in markup. No new attached property is added. FormatThemeResourceReference stays because ThemeResourceProbe (Resolve ThemeRef through WinUI instead of reading theme dictionaries #1633) still uses it.
  • Simpler than the Style path. The app's own Style is never touched, so a Style for a third-party control type is now kept too, where the Style path had to replace it and log a warning. A key is passed as is, so one with both quote characters, a tab or a line break now binds instead of being skipped.
  • InteractionStates keeps main's restore (capture when a state takes the property, restore only if it still holds the state's brush, rebind an app Binding). On top of that, a property Reactor theme-binds gets its binding back when the state ends, instead of the brush the binding had resolved to, which would pin that theme.
  • A key that changes to one WinUI can't find now releases the property, instead of keeping the previous key's brush on as if it were the new key's.

Precedence findings

The Style sat below local values, while the binding sits at local precedence. Every render applies setters and element properties first, then modifiers, then theme bindings. Without extra care the ThemeRef would win over things that beat it before. So the following rules keep the old winners.

  • An explicit brush modifier for the same property wins in either call order. That includes a modifier on a layer that shares the control, such as a keyed Memo or a flyout target. The modifier suppresses the binding instead of forgetting it, so removing the modifier brings the ThemeRef back.
  • A local value Reactor didn't bind, such as a .Set setter or an element property like Border.Background, is left alone.
  • If a setter or element property writes over a binding during a render, Reactor hands the property over. Update compares the bound values before and after the element's setters run, before its own RequestedTheme modifier applies. A later key change, resource refresh or ThemeRef removal then leaves that brush alone. A brush Reactor installed itself in that window, for example from a nested layer, doesn't count as a takeover. Neither does a change of the control's effective theme in that window, which WinUI re-resolves natively.
  • A binding that's already in place isn't installed again on an ordinary render. The one exception is a resource-refresh pass (Theme.NotifyResourcesChanged). A binding resolves its key once and only re-resolves on a theme change or reparent, so an edited dictionary entry needs it installed again.
  • While an InteractionStates state holds a property, ThemeRef changes don't overwrite the hover brush. A key change or refresh updates what the state restores, a dropped ThemeRef makes the state clear the property, and a ThemeRef declared during the hover is installed when it ends.

ReadLocalValue on a bound property now returns the resolved brush instead of unset.

Resolution timing findings

Mount binds before the control is parented, so the key first resolves against the app theme. A spike confirmed WinUI re-resolves on parenting. Under a Dark ancestor the value flips to the Dark brush when the control joins the tree, and it follows later ancestor RequestedTheme toggles. ThemeResourceBinding_MountResolvesAncestorTheme pins this.

A key that can't be resolved makes SetThemeResourceBinding throw COMException, and a value the property can't hold throws ArgumentException. Both are logged through DiagnosticLog.SwallowedError(LogCategory.Theme, ...), the property is left unset, and a later render binds it once the key exists. A key that exists only in an ancestor's Resources fails the same way at mount, as it did when the XamlReader path parsed it.

ThemeRef.Resolve (#1534) isn't changed here. #1633 made it resolve through a WinUI probe, and #1635 moves that probe onto this API once this PR has main. This PR implements Option B of Proposal #22 in docs/specs/proposals/winui3-integration.md.

Linked issue / spec

Part of the #1125 stack. Builds on #1636 and #1633. Related to #522 and #758.

Test plan

  • ThemeRefStyleFixtures from Fix ThemeRef PaneBackground, InteractionStates restore, author Style and key quoting on the Style path #1636 (the stable-SDK behavior checks) all pass and still check the same behaviors. Assertions that inspected the Style itself now check the bound value.
    • .Style.BasedOn checks became checks that .Style is still the app's Style.
    • "No local value" checks became checks that the local value isn't the state's or the replaced brush, since a binding is a local value.
    • The ownership-marker checks in the pool fixture became checks that the binding was cleared.
    • The cache-key collision fixture now checks that each button binds only its own properties.
    • The third-party Style fixture now expects the app's Style to stay rather than be replaced.
    • The unrepresentable-key fixture became ThemeRefStyle_MissingKeySkipsOnlyItsProperty, because every key can now be bound. The tab key moved into the key-quoting fixture, where it binds.
  • ThemeResourceBindingFixtures.cs has 25 selftests for precedence, hand-over, nested layers, mount-time resolution, unknown keys, pool return, InteractionStates restore for Background, Foreground and BorderBrush, and SplitView.PaneBackground.
  • Mutation-checked on this head. Dropping the release on a failed key change fails ThemeRefStyle_BadKey_Switch_BadKeyDropsOldBrush, and dropping the theme-binding restore in InteractionStates fails the six ThemeRefStyle_Hover_*_NormalRestored and ThemeLiveAfterRestore checks.
  • dotnet build src\Reactor\Reactor.csproj --no-restore -c Release -p:Platform=x64 passed with 0 errors and the 2 expected MSB3277 warnings.
  • dotnet build tests\Reactor.AppTests.Host --no-restore -c Debug -p:Platform=x64 and -c Release both passed, with only MSB3277 warnings.
  • dotnet test tests\Reactor.Tests --no-build -p:Platform=x64 passed 16,225 tests, with 0 failed and 18 skipped.
  • dotnet run --project tests\Reactor.AppTests.Host --no-build -c Debug -p:Platform=x64 -- --self-test --filter <prefix> passed with 0 failures for ThemeRefStyle_ (114), ThemeResourceBinding_ (87), ThemeRef (161), ThemeBindingsSkip (16), Issue522 (51), Issue675 (36), StructuralSkip (14), UseMemoCells_ (4), CoreCov_ (131), BorderTheme (50) and PanelBorder (121).
  • Locally ModifierTransform_Handoff_InteractionStates times out, as it does on the base, and every CurveLinear_*_ProgressTracksTime check fails, including the ones with no InteractionStates or theme code, because animations finish instantly on this machine. CI runs both.

Risk / breaking changes

  • ReadLocalValue on a ThemeRef-bound property now returns the resolved brush.
  • A Style for a third-party control type is no longer replaced by a ThemeRef.
  • A ThemeRef key that changes to an unknown key now clears the property instead of keeping the old brush.
  • Two narrow cases where a value that's not Reactor's can still be replaced, because the binding's provenance can't be observed.
    • A brush app code writes directly to a bound property outside a render still counts as Reactor's.
    • A setter that changes the control's RequestedTheme and writes the same brush in one render, while the ThemeRef key also changes, isn't seen as a takeover.
    • With the old Style, a local value always won in both cases.
  • Requires the experimental Windows App SDK, same as Build Reactor's DataTemplates from code instead of parsing markup #1125.

@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build metrics

Artifact sizes for 88d30a9 vs the base branch (6ba6a55).

Packages (compressed .nupkg)

Artifact base PR Δ
Microsoft.UI.Reactor.nupkg 2.09 MB 2.09 MB +783 B (+0.04%) ≈
Microsoft.UI.Reactor.Advanced.nupkg 528.6 KB 528.7 KB +9 B (0.00%) ≈
Microsoft.UI.Reactor.Devtools.nupkg 287.8 KB 287.8 KB +5 B (0.00%) ≈

Assemblies in Microsoft.UI.Reactor

Artifact base PR Δ
Reactor.Analyzers.dll 437.5 KB 437.5 KB +0 B (0.00%) ≈
Reactor.dll 2.83 MB 2.83 MB -1.00 KB (-0.03%) ≈
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%) ≈

No size change beyond the noise floor. ✅

✅ 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.

Comment thread src/Reactor/Core/Reconciler.cs Fixed
Comment thread src/Reactor/Core/Reconciler.cs Fixed
Comment thread src/Reactor/Core/Reconciler.cs Fixed
Comment thread src/Reactor/Core/Reconciler.cs Fixed
@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🧪 Merged coverage

Coverage for 88d30a9 vs the base branch (28a8722) — unit + selftest merged.

Metric base PR Δ
Line 88.70% 88.70% 0.00 pp ≈
Branch 45.68% (18380/40239) 45.55% (18367/40323) -0.13 pp ⚠️

✅ 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.

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

ThemeRef cleanup and rebinding can erase explicit brush overrides or active hover styling, leaving controls with incorrect brushes.

3 open issues
What changed in this PR

This PR replaces Reactor’s parsed ThemeRef styles with native SetThemeResourceBinding calls, preserving app-authored styles while keeping theme values live. It depends on the experimental SDK upgrade in #1125.

Changes:

  • Tracks bindings per control and clears them during updates and pooling.
  • Adds SplitView.PaneBackground support and restores live bindings after interaction states.
  • Adds regression fixtures, updates existing assertions, and removes obsolete style-cache tests.
File Description
tests/​Reactor.Tests/​StyleCacheTests.cs Removes obsolete style-cache tests.
tests/​Reactor.Tests/​ReconcilerCacheKeyTests.cs Removes cache-key tests.
tests/​Reactor.Tests/​AnalyzerTests/​ModifierTableIntegrityTests.cs Checks the new property-mapping implementation.
tests/​Reactor.AppTests.Host/​SelfTest/​SelfTestFixtureRegistry.cs Registers new and renamed fixtures.
tests/​Reactor.AppTests.Host/​SelfTest/​Fixtures/​ThemeResourceBindingFixtures.cs Adds precedence, style preservation, and live-binding tests.
tests/​Reactor.AppTests.Host/​SelfTest/​Fixtures/​PanelBorderFixture.cs Updates border assertions for native bindings.
tests/​Reactor.AppTests.Host/​SelfTest/​Fixtures/​Issue522TextBlockStyleResetFixture.cs Updates binding-removal and isolation regressions.
tests/​Reactor.AppTests.Host/​SelfTest/​Fixtures/​CoreCoverageFixtures.cs Updates comments describing theme binding coverage.
tests/​Reactor.AppTests.Host/​SelfTest/​Fixtures/​BorderThemeBackgroundFixture.cs Checks resolved local brush values.
src/​Reactor/​Hosting/​ReactorHost.cs Updates theme-change comments.
src/​Reactor/​Hooks/​UseMemoCells.cs Updates comments explaining native theme resolution.
src/​Reactor/​Core/​Reconciler.Update.cs Passes modifier and refresh context to binding updates.
src/​Reactor/​Core/​Reconciler.Mount.cs Passes modifier context when installing bindings.
src/​Reactor/​Core/​Reconciler.cs Implements native bindings, ownership tracking, and interaction restoration.
src/​Reactor/​Core/​ElementPool.cs Clears tracked bindings before reuse.
src/​Reactor/​Core/​Element.cs Updates skip-behavior documentation.
src/​Reactor/​Core/​ChildDiffHints.cs Updates theme-sensitivity comments.
src/​Reactor.Analyzers/​NoOpModifierAnalyzer.cs Updates a helper name in documentation.
CHANGELOG.md Documents observable behavior changes and fixes.

Review effort: Balanced

Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved

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

Theme-binding transitions can overwrite active interaction or explicit brushes and restore stale brushes after removal, leaving unresolved UI-state regressions.

5 open issues
1 resolved since last review

Review effort: Balanced

Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Fixed

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.

Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved

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

ThemeRef ownership and hover-state bugs can leave stale or cleared brushes after updates, while several fixtures have theme-dependent expectations that fail under a Dark application theme.

4 open issues
4 resolved since last review

Review effort: Balanced

Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved
Comment thread src/Reactor/Core/Reconciler.cs Resolved

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 ownership guard misses explicit setter writes during theme transitions, allowing a new binding to overwrite an explicit brush and hiding nested Flyout setter changes.

1 open issue
4 resolved since last review

Review effort: Balanced

Comment thread src/Reactor/Core/Reconciler.cs Resolved
@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) removed the ready-for-review Agent work and technical checks complete; awaiting review, not approval or merge label Nov 20, 2026
Alexandre Zollinger Chohfi (azchohfi) added a commit that referenced this pull request Nov 20, 2026
…and key quoting on the Style path (#1636)

* Fix ThemeRef PaneBackground, InteractionStates restore, author Style and key quoting on the Style path

Port the #1618 ThemeRef fixes that don't need SetThemeResourceBinding, keeping the
XamlReader {ThemeResource} Style:

- SplitView.PaneBackground(ThemeRef) maps to the pane background, and the descriptor
  clears a removed brush. A loaded SplitView rejects any Style not BasedOn
  DefaultSplitViewStyle (E_INVALIDARG), so the themed Style is built on it.
- InteractionStates captures the normal brush lazily and, on restore, clears a property
  that had no local value instead of writing back a brush captured at setup.
- The themed Style is built BasedOn the control's own Style (setter, ApplyStyle, named
  styles), targeting the control's exact type, cached per stamped base id, and
  ClearThemeBindings restores the base.
- ThemeRef keys are quoted and escaped in the setter value.

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

* Address pr-review findings

- Escape '|', '=' and '\' in the themed-Style cache key so a resource key containing
  them can't share a cached Style with a different binding set.
- InteractionStates recapture the normal brush when a re-render replaced the state's
  brush mid-state, so a later press/release restores the current brush.
- Guard the TryApplyBasedStyle rollback so nothing escapes into reconcile, and fall
  back to the unbased themed Style (warning once) when an app Style can't be a
  BasedOn of the control's WinUI type, instead of failing on every render.
- Reset the based-Style cache at its cap instead of freezing it.
- Read the base from the themed Style's BasedOn instead of an extra attached DP.
- Check XML characters by hand rather than with XmlConvert (keeps System.Xml out of
  ThemeRef apps); bound, escape and name the property in the bad-key warning.
- Filter the new catch clauses (OutOfMemory/StackOverflow pass through).
- Tests: Pressed sequences, mid-hover re-render, SplitView update/skip re-renders,
  unrepresentable key, cache-key collision, third-party Style fallback.
- Docs: CHANGELOG cites PR #1636, notes PaneBackground removal and the fallback;
  styling guide narrows the BasedOn claim.

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

* Address review round 1

- A ThemeRef whose key becomes unrepresentable now takes off the themed Style a
  previous render applied, restoring the app's Style, instead of keeping the old brush.
- A XamlReader parse failure (such as a missing resource key) no longer marks the
  app's base Style incompatible; only a failed apply does.
- Skip ThemeRefStyle_ThirdPartyStyleFallsBack under NativeAOT, like the Issue142
  fixtures that mount the same third-party control (no XAML metadata provider).

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

* Address review round 2

Restore a binding an InteractionStates brush wrote over: on exit, re-apply the
captured BindingExpression's ParentBinding instead of clearing the property, so a
bound Background/Foreground keeps following its source.

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

* Capture the binding through GetBindingExpression for the AOT build

Under NativeAOT the raw ReadLocalValue object for a bound property doesn't project as
a BindingExpression, so the InteractionStates restore cleared the binding there
(AOT Selftests: ThemeRefStyle_Bound_Restored). Capture the Binding through the typed
FrameworkElement.GetBindingExpression when the state takes the property over, and
restore it with SetBinding. Verified with a local NativeAOT publish.

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

* Address review round 4

Clear Reactor's themed-Style ownership marker when a control returns to the pool
(ElementPool.CleanElement now calls ClearThemeBindings), so a pooled control holds no
reference to the previous renter's themed Style.

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

---------

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

ApplyThemeBindings now binds each mapped property (Background, Foreground,
BorderBrush, SplitView.PaneBackground) with FrameworkElement.SetThemeResourceBinding,
the code equivalent of {ThemeResource}, instead of building a Style from a XAML
string. Ownership is tracked per property in ReactorState.ThemeResourceBindings, so
a dropped ThemeRef or a pooled control clears only what Reactor bound, and the
precedence the old Style had (explicit brush modifiers, setters and element
properties win) is kept at local-value precedence.

This replaces the Style path PR #1636 shipped on the stable SDK and keeps its
behavior checks (ThemeRefStyleFixtures). Removed with it: the themed-Style caches,
the ownership marker, the BasedOn base-style stamping and fallback, the
DefaultSplitViewStyle workaround and the unrepresentable-key warning, since no
Style is written and a key needs no quoting. FormatThemeResourceReference stays
for ThemeResourceProbe. InteractionStates keeps main's restore and also puts back
a theme binding the state wrote over, instead of its resolved brush. A key that
changes to one WinUI can't find now releases the property instead of keeping the
previous key's brush.

Stacks on #1125 (experimental Windows App SDK).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 0008bac9-a08b-4ee8-9f96-505c6f6f28b0

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.

2 participants