Skip to content

Keep one DynamicResource registration per specificity - #38152

Merged
kubaflo merged 4 commits into
dotnet:inflight/currentfrom
otretiak:fix/dr-specificity-main
Sep 4, 2026
Merged

kubaflo merged 4 commits into
dotnet:inflight/currentfrom
otretiak:fix/dr-specificity-main

Conversation

@otretiak

@otretiak otretiak commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Description of Change

Reopened against main as requested in #38103.

Element stored a single (key, specificity) pair per BindableProperty, so a
{DynamicResource}-valued Setter inside a VisualState overwrote the registration a style
had installed when the state was entered (OnSetDynamicResource replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks a style's), and
Setter.UnApply then removed the entry outright when the state was left.

From that point Element.OnResourcesChanged never saw the property again: the element stopped
following the resource for the rest of its lifetime, back in the default state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened to be resolved at the
moment the state was entered.

BindableObject.RemoveDynamicResource(BindableProperty, SetterSpecificity) already accepted a
specificity and discarded it, while its siblings RemoveBinding(property, specificity) and
ClearValue(property, specificity) honour theirs.

This stores the registrations in SetterSpecificityList<string> — the same structure Values and
Bindings already use — so each specificity keeps its own entry:

  • entering a state adds the state's registration without disturbing the style's;
  • leaving it removes only that one and republishes the next one down, so the property keeps
    tracking;
  • BindableContextAttributes.IsDynamicResource is cleared only once the last registration for the
    property is gone.

SetterSpecificityList<T> also gains GetValueAt/GetSpecificityAt, because Element has to
enumerate every registered key, not just the effective one — GetMergedResources and both
OnResourcesChanged overloads need all of them.

Issues Fixed

Fixes #38069

Tests

DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration walks the full
cycle on a Button whose style paints BackgroundColor from one dynamic resource and whose
Disabled state paints it from another: enabled colour, disabled colour, back to the enabled
colour, and then a change to the enabled resource must still reach the element.

Without the change that last assertion fails — Expected: Red, Actual: Blue, the element frozen on
the value resolved before the state was entered (verified by reverting only the three product files
to main and re-running the test).

Controls.Core.UnitTests on this branch: 5645 passed, 30 skipped, 0 failed.

The same change was verified against release/10.0.1xx-sr10 in #38103 (5716 passed, 0 failed); the
two branches now carry the identical patch.

Note on the force-push

This branch was originally written against main while it still carried the accidental net11.0
payload from #37995, where SetterSpecificityList<T> is a struct. #38155 reverted that payload, so
the branch has been rebuilt on top of current main (c478f6b4) with the class-based version of
the patch — the same one that was validated on release/10.0.1xx-sr10.

@github-actions

github-actions Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 38152

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 38152"

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service dotnet-policy-service Bot added the community ✨ Community Contribution label Sep 3, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @@otretiak! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @otretiak! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@github-actions github-actions Bot added the area-xaml XAML, CSS, Triggers, Behaviors label Sep 3, 2026
@otretiak

otretiak commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

@otretiak please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@dotnet-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@dotnet-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@dotnet-policy-service agree company="Microsoft"

Contributor License Agreement

@dotnet-policy-service agree

@kubaflo kubaflo 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.

Could you please resolve conflicts?

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

### Description of Change

Generalizes the existing Darc-based official release pipeline so it can
publish shipping NuGet packages from allowlisted non-workload
repositories, initially `dotnet/android-libraries`, while preserving the
existing MAUI workload-release path.

- Keeps the existing free-text repository and commit inputs.
- Infers workload behavior for `dotnet/android`, `dotnet/macios`, and
`dotnet/maui`.
- Preserves the existing first-match BAR resolution behavior for all
repositories, then validates the resolved repository and gathers using
the dynamically returned BAR build ID.
- Keeps workload gathering, workload-set promotion, pack-before-manifest
ordering, approvals, and publishing behavior isolated from the
non-workload path.
- Gathers only shipping NuGet assets and rejects malformed packages,
duplicate filenames, duplicate ID/version identities, unexpected
packages, and workload manifests on non-workload releases.
- Supports include/exclude package filters for both workload and
non-workload releases.
- Filters exact ID/version pairs already on NuGet.org during preparation
and again immediately before publishing, preventing reruns and packages
published between those phases from causing HTTP 409 conflicts.
- Supports repeating the same non-workload BAR release after partial
publication: Darc may no longer download assets whose BAR location moved
to NuGet.org, so missing selected assets are accepted only when their
exact identity is confirmed on NuGet.org. Other missing or unavailable
packages fail closed.
- Publishes the exact selected and staged package lists as the
`NuGetReleaseAudit` artifact before manual approval.
- Uses the existing `1ES.PublishNuget@1` task and `nuget.org
(dotnetframework)` service connection, then verifies every expected
package on NuGet.org.
- Supports a non-mutating dry run with `pushPackages: false`.

### Dry-run inputs

```yaml
ghOwner: dotnet
ghRepo: android-libraries
commitHash: <ANDROID_LIBRARIES_COMMIT_WITH_BAR_BUILD>
pushWorkloadSet: false
pushNugetOrg: true
pushPackages: false
```

Queue `dotnet-maui-release` against this PR branch after it appears in
the internal `dotnet-maui` mirror. The run performs BAR resolution,
gathering, package validation/filtering, and audit artifact publication
without promotion or NuGet publishing.

### External setup

Before enabling a real push, release owners must verify that the
existing `nuget.org (dotnetframework)` service connection owns every
package ID in the audit artifact and has sufficient scope/quota.
Android-libraries BAR builds contain per-build deltas rather than the
union of channel assets, so each pending BAR build must be released in
commit order.

### Validation

- [Successful `dotnet/android-libraries` NuGet.org release
run](https://dev.azure.com/dnceng/internal/_build/results?buildId=3063121&view=results):
BAR resolution, gathering, filtering, audit publication, package push,
and NuGet.org verification all succeeded.
- The overall build is `partiallySucceeded` only because 1ES production
branch/source validation reported non-blocking errors for running the
test from this PR branch instead of an approved production branch.
- Focused release pipeline and NuGet availability Pester suites.
- YAML parsing and whitespace validation.

### Issues Fixed

N/A

---------

Copilot-Session: 2933e733-3bed-4524-ae14-f7ad1c7959e6
Element stored a single (key, specificity) pair per BindableProperty, so a
{DynamicResource}-valued setter in a VisualState overwrote the registration a
style had installed on entry, and Setter.UnApply removed the entry outright on
exit. From then on OnResourcesChanged never saw the property again: the element
stopped following the resource for the rest of its life, in the default state,
with no way to recover. A theme switch after that leaves the element on whatever
value happened to be resolved when the state was entered.

RemoveDynamicResource already accepted a SetterSpecificity and discarded it,
while its siblings RemoveBinding and ClearValue honour theirs.

Store the registrations in SetterSpecificityList<string> -- the same structure
Values and Bindings already use -- so each specificity keeps its own entry.
Leaving a state removes only that state's registration and republishes the next
one down; the flag on the property context is cleared only once the last
registration is gone.

Fixes dotnet#38069

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@otretiak
otretiak force-pushed the fix/dr-specificity-main branch from b43e2fb to 4720487 Compare September 4, 2026 09:16
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 4, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

AI Review Summary

@otretiak — new AI review results are available based on commit 4720487.

Gate Passed Confidence Unknown Platform Android


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ✅ PASSED

Platform: ANDROID · Base: main · Merge base: f05f0f39

Test Without Fix (expect FAIL) With Fix (expect PASS)
🧪 DynamicResourceTests DynamicResourceTests ✅ FAIL — 103s ✅ PASS — 103s
🔴 Without fix — 🧪 DynamicResourceTests: FAIL ✅ · 103s

Error-relevant lines (filtered from the build log):

     at Microsoft.Maui.Controls.Core.UnitTests.DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration() in /_/src/Controls/tests/Core.UnitTests/DynamicResourceTests.cs:line 427
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
🟢 With fix — 🧪 DynamicResourceTests: PASS ✅ · 103s

(no coded error found; showing last 1200 chars)

ainKey [30 ms]
  Passed ParentSetAppliesDynamicResourceFromParentWithoutListener [< 1 ms]
  Passed ParentSetAppliesImplicitLabelStyleWithoutListener [9 ms]
  Passed ParentSetAppliesBindableObjectResourceBindingContextWithoutListener [5 ms]
  Passed TestDynamicResourceOverride [38 ms]
  Passed ReparentResubscribe [6 ms]
  Passed FallbackToApplicationCurrent [30 ms]
  Passed AddingAResourceDictionaryTriggersValueChangedForExistingValues [< 1 ms]
  Passed RemoveDynamicResourceStopsUpdating [1 ms]
  Passed ParentSetAppliesMultipleDynamicResourcesInFullSnapshotOrderWithoutListener [39 ms]
  Passed SetResourceOnParentTriggerSetValue [< 1 ms]
  Passed VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration [17 ms]
  Passed ClearedResourcesDoesNotClearValues [< 1 ms]
  Passed TestDynamicResource [< 1 ms]
  Passed ParentSetDoesNotOverrideLocalDynamicResourceValue [< 1 ms]
  Passed ResourcesCanBeChanged [< 1 ms]
[xUnit.net 00:00:02.62]   Finished:    Microsoft.Maui.Controls.Core.UnitTests
  Passed ParentSetMergesStyleClassResourcesWithoutListener [2 ms]
  Passed SettingResourceTriggersValueChanged [< 1 ms]
Test Run Successful.
Total tests: 20
     Passed: 20
 Total time: 3.4094 Seconds
📁 Fix files reverted (3 files)
  • src/Controls/src/Core/BindableObject.cs
  • src/Controls/src/Core/Element/Element.cs
  • src/Controls/src/Core/SetterSpecificityList.cs

📋 Pre-Flight — Context & Validation

PR #38152 Pre-Flight

Context

  • Title: Keep one DynamicResource registration per specificity
  • Issue: #38069, “A {DynamicResource}-valued Setter in a VisualState permanently destroys the property's dynamic-resource registration”
  • Target branch/platform: main; behavior is cross-platform, with android as the requested test platform.
  • Materialized review commit: 2c07ba1fe7ca968566b47e4cf988b395a5919a64
  • Merge base: f05f0f39631eae73089be188d890318b4732e2dc

Problem

Element records only one dynamic-resource (key, specificity) pair per BindableProperty. A higher-specificity VisualState setter overwrites a style's registration. When that state is left, Setter.UnApply removes the property registration entirely, so subsequent changes to the style's resource never reach the element.

Existing PR Approach

The PR changes the per-property registration to SetterSpecificityList<string>, passes specificity through OnRemoveDynamicResource, removes only the departing specificity, republishes the next effective registration, and clears IsDynamicResource only after the final registration is gone. It adds indexed accessors to SetterSpecificityList<T> so all registered resource keys can be enumerated.

Changed product files:

  • src/Controls/src/Core/BindableObject.cs
  • src/Controls/src/Core/Element/Element.cs
  • src/Controls/src/Core/SetterSpecificityList.cs

The added regression test is:

  • src/Controls/tests/Core.UnitTests/DynamicResourceTests.cs
  • DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration

Bounded Validation

Primary command:

dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --configuration Debug --logger "console;verbosity=normal" -p:TreatWarningsAsErrors=false --filter "DynamicResourceTests"

The prior gate already established that this test class fails against the broken baseline and passes with the PR fix; gate verification must not be repeated. The regression-risk phase found no additional mandatory regression tests.

Try-Fix Constraints

Each candidate must use a mechanism meaningfully different from the PR and all earlier candidates, may modify only the three product files listed above after baseline establishment, gets one test pass plus at most one focused correction/retest, must perform the try-fix skill's inline expert self-review, capture its complete diff and test evidence, and restore through pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore.


🔬 Code Review — Deep Analysis

Expert Evaluation of the Submitted PR Fix

Reviewed candidate: pr at 2c07ba1fe7ca968566b47e4cf988b395a5919a64

Code assessment: The submitted fix replaces Element's single dynamic-resource registration per BindableProperty with a specificity-aware SetterSpecificityList<string>. Removal now targets only the departing specificity and republishes the next effective registration; resource lookup and change propagation enumerate every retained key. The regression test exercises the style → VisualState override → style restoration cycle and verifies that a later resource update still reaches the control.

Expert findings: No actionable error, warning, or suggestion was found on the submitted diff. The required inline findings artifact is therefore an empty JSON array.

Blast radius: This changes shared Theme/Style infrastructure for all Element instances that use dynamic resources, but introduces no startup path, platform-specific handler plumbing, or static/shared state. The implementation reuses the same specificity container already used by values and bindings.

Failure-mode assessment: Removing a non-effective registration preserves the current effective registration; removing the effective registration republishes the next registration; removing the final registration clears the dynamic-resource marker. Multiple keys are retained for merged-resource lookup and both resource-change propagation paths, avoiding stale fallback registrations after VisualState transitions.

Review verdict: NEEDS_DISCUSSION with low confidence only because the expert-review environment could not establish a conclusively green required-check state. There is no code-level blocker or actionable feedback to apply. The pipeline-provided trusted Gate separately records that the regression fails without the fix and passes with it.


🛠️ Try-Fix — Analysis & Comparison

Try-Fix Candidates

Candidate 1 — Style-Key Fallback Restoration

Model: gpt-5.3-codex

Approach: Retain the currently active dynamic-resource registration plus one dedicated fallback style key, then restore that fallback when a transient VisualState override is removed.

Difference from the PR: PR #38152 stores all registrations by specificity in SetterSpecificityList<string>. Candidate 1 instead models only an active/fallback pair and would republish the fallback directly, avoiding a general per-specificity registry and enumeration.

Result: Blocked

Baseline establishment rejected the pre-existing dirty tracked worktree before .github/.baseline-state.json or its authoritative RevertedFiles allow-list could be created. No product file was edited and the primary test was not run.

Diff: Empty.

Test command: Not run because baseline establishment failed.

dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --configuration Debug --logger "console;verbosity=normal" -p:TreatWarningsAsErrors=false --filter "DynamicResourceTests"

Self-review: 0 findings; there was no candidate diff.

Restore: pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore completed with No baseline state found / Restored False, which is the expected no-state result because the attempt made no edits.

Full candidate record: ../try-fix-1/content.md

Candidate 2 — Reconstruct Registration From Applied Style Metadata

Model: gpt-5.6-sol

Approach: When a VisualState dynamic-resource setter is removed, invalidate and replay the applicable already-applied style declaration, deriving the underlying resource key from authoritative style metadata instead of preserving displaced registrations.

Difference from earlier approaches: PR #38152 retains every key in a per-specificity registry, while Candidate 1 planned one retained fallback key. Candidate 2 would retain neither; it would reconstruct the underlying registration on state exit by replaying style metadata.

Result: Blocked

Baseline establishment again rejected the pre-existing dirty tracked worktree and did not create .github/.baseline-state.json. Without an authoritative RevertedFiles allow-list, the candidate correctly made no product edits and did not run the primary test.

Diff: Empty.

Test command: Not run because baseline establishment failed.

dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --configuration Debug --logger "console;verbosity=normal" -p:TreatWarningsAsErrors=false --filter "DynamicResourceTests"

Self-review: 0 findings; there was no candidate diff.

Restore: pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore completed with No baseline state found / Restored False, which is the expected no-state result because the attempt made no edits.

Full candidate record: ../try-fix-2/content.md

Aggregate Result

Both permitted attempts are complete. They produced two mechanism-level alternative designs, but neither could be implemented or tested because the mandatory baseline helper rejected the pre-existing dirty tracked worktree before creating a safe edit allow-list. No validated alternative candidate is available for STEP 5b; the PR's existing fix remains the only gate-validated implementation in the recorded evidence.


🏁 Report — Final Recommendation

✅ Final Recommendation: APPROVE

Winner: pr

The submitted PR is the only implemented alternative with direct regression evidence. The trusted Gate proves that DynamicResourceTests fails on the broken baseline and passes with the submitted fix, including VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration. The expert review found no actionable code issue, and the regression cross-reference found no overlap with recent labeled bug-fix changes.

Comparative Ranking

Rank Candidate Implementation Regression evidence Expert assessment Decision
1 pr Complete specificity-aware registry, selective removal, fallback republication, all-key resource propagation, and regression test PASS — trusted Gate: fails without fix, all 20 DynamicResourceTests pass with fix No actionable findings Winner
2 pr-plus-reviewer Identical to pr; the expert supplied no actionable refinement and reviewer.patch is empty Same submitted-fix Gate evidence; no redundant candidate test was required or run No improvement over pr Loses the identity-candidate tie-break to the already-submitted PR
3 try-fix-1 Proposed active-plus-one-fallback key model; no implementation and empty diff Blocked / not run because baseline establishment rejected the dirty worktree No candidate code existed to review Below validated candidates
4 try-fix-2 Proposed reconstruction from applied style metadata; no implementation and empty diff Blocked / not run because baseline establishment rejected the dirty worktree No candidate code existed to review Below validated candidates

Why pr Wins

The fix addresses the underlying state model rather than reconstructing lost state after a VisualState transition. Each specificity retains its own dynamic-resource key, so removing one registration naturally reveals the next effective registration, while the final removal alone clears IsDynamicResource. Enumerating retained keys in merged-resource lookup and both resource-change paths keeps inactive registrations current without special-casing style or VisualState metadata.

pr-plus-reviewer is behaviorally and textually the same candidate because the expert review had nothing actionable to add. Selecting it would falsely imply that the submitted PR needs an unsubmitted change. Both try-fix-* entries are mechanism proposals only; neither has a diff or regression result, so neither can outrank the Gate-validated implementation.

Review and Validation Reconciliation

The expert pass reported NEEDS_DISCUSSION with low confidence solely because its environment could not establish a conclusively green required-check state; it reported no code-level error, warning, suggestion, or unresolved prior code-review finding. For this bounded comparative decision, the supplied trusted Gate permits approval and directly validates the changed behavior. This recommendation does not claim that the full PR CI suite is green.

No candidate failed the regression test. The two alternative candidates were blocked before testing, which ranks them below the passing submitted fix.


📱 UI Tests — Button,Label,Layout

Detected UI test categories: Button,Label,Layout

✅ Deep UI tests — 360 passed, 0 failed, 7 skipped across 3 categories on platform-pool agent (replaces in-process counts above).

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
Button 71/73 (2 skipped) ✓ —
Label 97/99 (2 skipped) ✓ —
Layout 192/195 (3 skipped) ✓ —
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)

🧭 Next Steps — review latest findings

No alternative fix was selected for this run. Review the session findings and CI results before merging.

@MauiBot MauiBot added s/agent-approved AI agent recommends approval - PR fix is correct and optimal s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Sep 4, 2026
@kubaflo
kubaflo changed the base branch from main to inflight/current September 4, 2026 21:58
Resolve the DynamicResourceTests.cs add/add content conflict by retaining both regression test groups.\n\nCo-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@kubaflo
kubaflo merged commit 954ac56 into dotnet:inflight/current Sep 4, 2026
2 of 4 checks passed
@github-actions github-actions Bot added this to the .NET 10 SR11 milestone Sep 4, 2026
kubaflo added a commit that referenced this pull request Sep 6, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
@otretiak
otretiak deleted the fix/dr-specificity-main branch September 7, 2026 07:51
kubaflo added a commit that referenced this pull request Sep 7, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Sep 8, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Sep 9, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Sep 11, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Sep 15, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Sep 18, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Sep 21, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Sep 27, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Sep 27, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Oct 3, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Oct 3, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Oct 6, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Oct 6, 2026
### Description of Change

Reopened against `main` as requested in #38103.

`Element` stored a single `(key, specificity)` pair per
`BindableProperty`, so a
`{DynamicResource}`-valued `Setter` inside a `VisualState` **overwrote**
the registration a style
had installed when the state was entered (`OnSetDynamicResource`
replaces the entry when the
incoming specificity is greater or equal, and a full-VSM setter outranks
a style's), and
`Setter.UnApply` then removed the entry outright when the state was
left.

From that point `Element.OnResourcesChanged` never saw the property
again: the element stopped
following the resource for the rest of its lifetime, back in the default
state, with no way to
recover. A theme switch afterwards leaves it on whatever value happened
to be resolved at the
moment the state was entered.

`BindableObject.RemoveDynamicResource(BindableProperty,
SetterSpecificity)` already accepted a
specificity and discarded it, while its siblings
`RemoveBinding(property, specificity)` and
`ClearValue(property, specificity)` honour theirs.

This stores the registrations in `SetterSpecificityList<string>` — the
same structure `Values` and
`Bindings` already use — so each specificity keeps its own entry:

- entering a state adds the state's registration without disturbing the
style's;
- leaving it removes only that one and republishes the next one down, so
the property keeps
  tracking;
- `BindableContextAttributes.IsDynamicResource` is cleared only once the
last registration for the
  property is gone.

`SetterSpecificityList<T>` also gains `GetValueAt`/`GetSpecificityAt`,
because `Element` has to
enumerate every registered key, not just the effective one —
`GetMergedResources` and both
`OnResourcesChanged` overloads need all of them.

### Issues Fixed

Fixes #38069

### Tests


`DynamicResourceTests.VisualStateDynamicResourceDoesNotDestroyTheStylesRegistration`
walks the full
cycle on a `Button` whose style paints `BackgroundColor` from one
dynamic resource and whose
`Disabled` state paints it from another: enabled colour, disabled
colour, back to the enabled
colour, and then a change to the enabled resource must still reach the
element.

Without the change that last assertion fails — `Expected: Red, Actual:
Blue`, the element frozen on
the value resolved before the state was entered (verified by reverting
only the three product files
to `main` and re-running the test).

`Controls.Core.UnitTests` on this branch: **5645 passed, 30 skipped, 0
failed**.

The same change was verified against `release/10.0.1xx-sr10` in #38103
(5716 passed, 0 failed); the
two branches now carry the identical patch.

### Note on the force-push

This branch was originally written against `main` while it still carried
the accidental `net11.0`
payload from #37995, where `SetterSpecificityList<T>` is a struct.
#38155 reverted that payload, so
the branch has been rebuilt on top of current `main` (`c478f6b4`) with
the class-based version of
the patch — the same one that was validated on `release/10.0.1xx-sr10`.

---------

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 7, 2026
@github-actions github-actions Bot modified the milestones: .NET 10 SR11, .NET 10 SR12 Oct 21, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-xaml XAML, CSS, Triggers, Behaviors community ✨ Community Contribution s/agent-approved AI agent recommends approval - PR fix is correct and optimal s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A {DynamicResource}-valued Setter in a VisualState permanently destroys the property's dynamic-resource registration

4 participants