Repository navigation
Bind ThemeRef properties with SetThemeResourceBinding instead of a parsed Style - #1618
Conversation
📦 Build metricsArtifact sizes for Packages (compressed .nupkg)
Assemblies in Microsoft.UI.Reactor
Assemblies in Microsoft.UI.Reactor.Advanced
Assemblies in Microsoft.UI.Reactor.Devtools
No size change beyond the noise floor. ✅ ✅ smaller / |
c9a56da to
ca13801
Compare
🧪 Merged coverageCoverage for
✅ higher / |
There was a problem hiding this comment.
🟡 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.PaneBackgroundsupport 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
There was a problem hiding this comment.
🟡 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
Explicit border brush is cleared when hover ends · New Removed ThemeRef brush resurfaces after a second hover cycle · New Theme changes overwrite a same-render explicit brush takeover · New Theme refresh overwrites the active hover brush Resource refresh overrides an enclosing explicit Foreground brush
1 resolved since last review
Review effort: Balanced
There was a problem hiding this comment.
🟡 Changes recommended
Active findings show theme-binding ownership and restoration bugs during wrapper removal, nested refreshes, and hover transitions that can display incorrect brushes or prevent later rebinding.
4 open issues
6 resolved since last review
Theme changes overwrite a same-render explicit brush takeover Removed ThemeRef brush resurfaces after a second hover cycle Explicit border brush is cleared when hover ends Theme refresh overwrites the active hover brush Resource refresh overrides an enclosing explicit Foreground brush Partial ThemeRef removal clears an explicit Background override
Review effort: Balanced
There was a problem hiding this comment.
🟡 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
f39437b to
234328a
Compare
…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
234328a to
88d30a9
Compare

Summary
ThemeRefmodifiers (.Background(Theme.X),.Foreground(...),.BorderBrush(...),.WithBorder(...),SplitView.PaneBackground(...)) now bind each property withFrameworkElement.SetThemeResourceBinding, the code equivalent of{ThemeResource}. Onmain,Reconciler.ApplyThemeBindingsbuilds a<Style>with{ThemeResource}setters as a XAML string, parses it withXamlReader.Load, caches it and assignsfe.Style, builtBasedOnthe app's own Style since #1636.This stacks on #1125 and can't merge before it.
SetThemeResourceBindingis an experimental WinUI API (spec microsoft/microsoft-ui-xaml#11229). It only exists on the2.6.6-experimentalchannel 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 asBasedOn, and quoted keys. This PR keeps every one of those behaviors and swaps the mechanism underneath.What changes
ApplyThemeBindingsbinds each mapped property and keeps a record on the control'sReactorState. 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 publicApplyThemeBindings(fe, bindings)signature is kept.ReactorAppliedThemeStyleownership marker,BuildCacheKeyandClearStyleCache, theBasedOnbase-style id stamping and the incompatible-base fallback, theDefaultSplitViewStyleworkaround for loaded SplitViews, and the warning for keys that can't be written in markup. No new attached property is added.FormatThemeResourceReferencestays becauseThemeResourceProbe(Resolve ThemeRef through WinUI instead of reading theme dictionaries #1633) still uses it.main's restore (capture when a state takes the property, restore only if it still holds the state's brush, rebind an appBinding). 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.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.
Memoor a flyout target. The modifier suppresses the binding instead of forgetting it, so removing the modifier brings the ThemeRef back..Setsetter or an element property likeBorder.Background, is left alone.RequestedThememodifier 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.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.ReadLocalValueon 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
RequestedThemetoggles.ThemeResourceBinding_MountResolvesAncestorThemepins this.A key that can't be resolved makes
SetThemeResourceBindingthrowCOMException, and a value the property can't hold throwsArgumentException. Both are logged throughDiagnosticLog.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'sResourcesfails 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 hasmain. This PR implements Option B of Proposal #22 indocs/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
ThemeRefStyleFixturesfrom 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.BasedOnchecks became checks that.Styleis still the app's Style.ThemeRefStyle_MissingKeySkipsOnlyItsProperty, because every key can now be bound. The tab key moved into the key-quoting fixture, where it binds.ThemeResourceBindingFixtures.cshas 25 selftests for precedence, hand-over, nested layers, mount-time resolution, unknown keys, pool return, InteractionStates restore for Background, Foreground and BorderBrush, andSplitView.PaneBackground.ThemeRefStyle_BadKey_Switch_BadKeyDropsOldBrush, and dropping the theme-binding restore in InteractionStates fails the sixThemeRefStyle_Hover_*_NormalRestoredandThemeLiveAfterRestorechecks.dotnet build src\Reactor\Reactor.csproj --no-restore -c Release -p:Platform=x64passed with 0 errors and the 2 expected MSB3277 warnings.dotnet build tests\Reactor.AppTests.Host --no-restore -c Debug -p:Platform=x64and-c Releaseboth passed, with only MSB3277 warnings.dotnet test tests\Reactor.Tests --no-build -p:Platform=x64passed 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 forThemeRefStyle_(114),ThemeResourceBinding_(87),ThemeRef(161),ThemeBindingsSkip(16),Issue522(51),Issue675(36),StructuralSkip(14),UseMemoCells_(4),CoreCov_(131),BorderTheme(50) andPanelBorder(121).ModifierTransform_Handoff_InteractionStatestimes out, as it does on the base, and everyCurveLinear_*_ProgressTracksTimecheck fails, including the ones with no InteractionStates or theme code, because animations finish instantly on this machine. CI runs both.Risk / breaking changes
ReadLocalValueon a ThemeRef-bound property now returns the resolved brush.RequestedThemeand writes the same brush in one render, while the ThemeRef key also changes, isn't seen as a takeover.