Skip to content

Fix resource additions in SourceGen Hot Reload - #39826

Merged
kubaflo merged 7 commits into
dotnet:candidate/11.0.1xx-sr2from
StephaneDelcroix:fix/xaml-hotreload-resource-dictionaries
Nov 11, 2026
Merged

kubaflo merged 7 commits into
dotnet:candidate/11.0.1xx-sr2from
StephaneDelcroix:fix/xaml-hotreload-resource-dictionaries

Conversation

@StephaneDelcroix

@StephaneDelcroix StephaneDelcroix commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

[!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 from this PR and let us know in a comment if this change resolves your issue. Thank you!

Description of Change

Fix source-generated incremental XAML Hot Reload resource additions. Adding an implicit Label style in App.xaml or a merged Styles.xaml now updates existing labels through the normal resource-change notifications.

The update writer skipped implicit styles because they have no explicit x:Key, treated explicit ResourceDictionary containers as resource values, and routed dictionary-root child additions through the generic content-property path.

The new addition paths reuse the normal inflation visitors and existing resource dictionary APIs: Add for eager resources and AddFactory for lazy resources, including implicit styles. Existing keys are guarded so these additions do not replace existing resources. Existing merged dictionaries, application-added resources, and live controls remain in place. Guards apply before constructing eager implicit styles as well as before registering lazy factories.

Added resources retain the normal lazy and x:Shared behavior, inherited x:DataType, and outer x:Reference bindings. Retained named elements are resolved through the live namescope (including explicit Content/Resources subtrees), and added eager named resources register their live names, compatible fields, and component IDs. Ancestor data-type context is cloned and normalized, including x:DataType="{x:Type local:Person}", without mutating the cached tree. Top-level keyed OnPlatform<T> additions are simplified through their synthetic dictionary parent so the selected platform value is inflated.

Resource-local and inherited mc:Ignorable declarations and ignore-prefix lists are preserved and normalized on cloned context. Pruning receives the synthetic dictionary parent, preventing generator crashes and runtime design-time property assignments. Added eager resources are created and registered before reference-dependent properties are initialized, allowing forward x:Reference between resources added in the same update. Live-name and compatible-field assignment also covers non-Element resources; dictionary-root field assignment is independent of the Element-only namescope and StyleId handling.

Addition-only implicit resource containers use guarded inflation rather than reconstructing unchanged resources; retained keyless class styles do not disqualify this path. Successfully inserted keyed resources merge into the existing resource-key bookkeeping so subsequent implicit removals keep working, without claiming keys that already existed at runtime. Other implicit update/removal edits keep the existing path. Hot Reload factories and deferred initializers, including nested resource factories, use local functions with explicit delegates to avoid introducing compiler-cached lambda fields during metadata updates. Names in separate template/style scopes are excluded from the outer reference map and live field assignment.

This revision removes the earlier Core, runtime registry, public API, ownership-snapshot, and binding-subscription changes. Production changes are confined to the source generator's update writer, patch-input/context plumbing, and directly related comparison/resource-factory helpers. It does not add general resource replacement/removal reconciliation or change ordinary runtime resource behavior.

Targets main. Broader resource-update and collection-reconciliation cases are outside this PR's scope.

Validation

Latest review follow-up, commit 17b1d8c04e, using the worktree's .NET 11 RC2 SDK and repository-absolute project paths:

DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --verbosity quiet

Passed: 708, failed: 0, skipped: 0.

DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~Maui37888Tests --verbosity quiet

Passed: 43, failed: 0, skipped: 0.

The expanded regressions reproduced the new failures before the fixes: resource-local and inherited ignore-prefix handling, forward references between eager additions, non-Element named-resource assignment, retained class-style preservation, and add-B/replace-with-C implicit resource bookkeeping. Collision regressions prepopulate the exact incoming keyed-resource or implicit-style key with a runtime factory, assert no factory realization or incoming construction during the update, and verify preservation through the following removal edit. Both implicit and explicit containers are covered, including eager and lazy implicit styles. Named dictionary-root cases exercise the SourceGen-only configuration: diagnostics/runtime fallback is disabled because the pre-existing fallback emits Element-only name lookups for dictionary roots.

Earlier follow-up regressions independently reproduced all five prior review findings before their fixes: null references to retained explicit subtrees, OnPlatform<Color> wrappers instead of selected colors, missing live names for added named resources, CS0103 for inherited x:Type data-type context, and unexpected existing-resource construction in implicit containers. Tests cover lazy/eager references, compatible named fields and chained additions, Android/iOS/MacCatalyst target-framework selection (including a dictionary root), configured resource identity/construction counts, and template/style scope isolation. Exercising nested resources followed by another addition also exposed a metadata-update crash; propagating the local-function factory form to nested additions fixes it.

The full suite includes real metadata-update cases for implicit and explicit App.xaml resource containers and a classless merged Styles.xaml dictionary. These verify existing/new consumers, keyed additions, and preservation of existing resources and controls. In the earlier worktree (repo=/Users/sde/Projects/Microsoft/maui-pr-39826), the following focused command reproduced all 3 failures before the generator fix, with an unchanged null background instead of red; all three pass in the latest full-suite run:

DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$repo/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~AddingApplicationResources_UpdatesExistingAndNewConsumers --logger 'console;verbosity=normal'

Formatted changed C# files with the repository settings:

dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs --verbosity quiet

Passed. git diff --check also passed. Native device/IDE validation was not run. Existing device/UI CI failures remain untriaged. No check runs or commit-status entries were available for the newly pushed head when checked. The earlier hosted test gate skipped metadata-update cases, so its result is not evidence that these runtime cases executed.

Issues Fixed

Partially addresses #36732: resource additions, including implicit styles.

StephaneDelcroix and others added 2 commits November 2, 2026 13:07
…t styles

Regenerate resource contents through the existing inflation visitors and reconcile XAML-owned entries into live dictionaries. Preserve runtime additions and lazy factories, notify removals, resolve ancestor resources, and avoid cached-lambda fields during metadata updates.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Preserve the current weak resource-change events and generated-field/name-update handling while integrating resource dictionary reconciliation. Follow the base branch's removal of Tizen API manifests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 2, 2026 12:13
@github-actions

github-actions Bot commented Nov 2, 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 -- 39826

Or

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

@azure-pipelines

This comment has been minimized.

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

Critical resource-update defects can break Hot Reload compilation, discard runtime resources, and leave stale references or incorrectly resolved values.

7 open issues
What changed in this PR

This PR extends .NET MAUI’s source-generated XAML Hot Reload to reconcile resource dictionaries and implicit styles on retained controls. It addresses the resource-related portion of #36732, without implementing the other complex-property reconciliation families.

Changes:

  • Regenerates resource subtrees through the normal inflation pipeline, including styles, converters, and templates.
  • Adds runtime dictionary reconciliation, resource-removal notifications, and cleanup when bindings replace dynamic resources.
  • Expands regression coverage for application resources, nested dictionaries, merged precedence, and template realization.
File Description
src/​Controls/​tests/​SourceGen.UnitTests/​XamlIncrementalHotReloadPipelineTests.cs Updates generated-code assertions for dictionary reconciliation.
src/​Controls/​tests/​SourceGen.UnitTests/​HotReload/​Maui37888Tests.cs Tests application implicit-style updates and reversals.
src/​Controls/​tests/​SourceGen.UnitTests/​HotReload/​AiAssisted/​TemplateAndSelectorHotReloadTests.DataTemplates.cs Verifies updated resource templates create new content.
src/​Controls/​tests/​SourceGen.UnitTests/​HotReload/​AiAssisted/​ResourceAndThemeHotReloadTests.Styles.cs Tests nested styles, non-shared factories, and BasedOn updates.
src/​Controls/​tests/​SourceGen.UnitTests/​HotReload/​AiAssisted/​ResourceAndThemeHotReloadTests.MergedDictionaries.cs Tests nested merged-dictionary reordering.
src/​Controls/​tests/​SourceGen.UnitTests/​HotReload/​AiAssisted/​NestedControlHotReloadTests.SameCompilation.cs Tests nested converter replacement and retained controls.
src/​Controls/​tests/​SourceGen.UnitTests/​HotReload/​AiAssisted/​NestedControlHotReloadTests.GeneratedRoots.cs Checks resource-update generation for nested roots.
src/​Controls/​tests/​SourceGen.UnitTests/​HotReload/​AiAssisted/​NestedControlHotReloadTests.cs Updates shared resource-generation assertions.
src/​Controls/​tests/​Core.UnitTests/​XamlComponentRegistryTests.cs Tests reconciliation, lazy resources, notifications, and fallback.
src/​Controls/​src/​Xaml/​XamlComponentRegistry.cs Tracks ownership snapshots and exposes dictionary updates.
src/​Controls/​src/​Xaml/​PublicAPI/​netstandard/​PublicAPI.Unshipped.txt Records the new reconciliation API for .NET Standard.
src/​Controls/​src/​Xaml/​PublicAPI/​net/​PublicAPI.Unshipped.txt Records the new reconciliation API for .NET.
src/​Controls/​src/​Xaml/​PublicAPI/​net-windows/​PublicAPI.Unshipped.txt Records the new reconciliation API for Windows.
src/​Controls/​src/​Xaml/​PublicAPI/​net-maccatalyst/​PublicAPI.Unshipped.txt Records the new reconciliation API for Mac Catalyst.
src/​Controls/​src/​Xaml/​PublicAPI/​net-ios/​PublicAPI.Unshipped.txt Records the new reconciliation API for iOS.
src/​Controls/​src/​Xaml/​PublicAPI/​net-android/​PublicAPI.Unshipped.txt Records the new reconciliation API for Android.
src/​Controls/​src/​SourceGen/​XamlNodeDiff.cs Retains previous complex nodes for subscription cleanup.
src/​Controls/​src/​SourceGen/​UpdateComponentCodeWriter.cs Regenerates resources and removes replaced dynamic-resource subscriptions.
src/​Controls/​src/​SourceGen/​SourceGenContext.cs Adds a local-resource-factory generation option.
src/​Controls/​src/​SourceGen/​SetPropertyHelpers.cs Emits local factories with explicit delegates for Hot Reload.
src/​Controls/​src/​SourceGen/​InitializeComponentCodeWriter.cs Registers initial dictionary ownership snapshots.
src/​Controls/​src/​Core/​ResourceDictionary.cs Reconciles resource contents and batches change notifications.
src/​Controls/​src/​Core/​Element/​Element.cs Adds ancestor fallback and clearing for removed resources.

Review effort: Balanced

Comment on lines +956 to +965
if (value == null)
{
this.TryGetResource(key, out value);
}
if (value == null)
{
foreach (var changedResource in changedResources)
ClearValue(changedResource.Item1, changedResource.Item2);
continue;
}
Comment on lines +170 to +174
else if (kvp.Key is ElementNode owner
&& owner.Properties.Keys.Any(name => name.LocalName == "Resources"))
dictionaryAccessor = $"{kvp.Value.ValueAccessor}.Resources";
if (dictionaryAccessor != null)
codeWriter.WriteLine($"global::Microsoft.Maui.Controls.Xaml.XamlComponentRegistry.RegisterResourceKeys({dictionaryAccessor}, new global::System.Collections.Generic.List<string>({dictionaryAccessor}.Keys).ToArray());");
Remove the Core reconciliation, registry API, snapshot, factory, and binding changes. Generate ordinary guarded Add calls for implicit styles and dictionary-root resource additions using the existing inflation visitors. Keep broader resource replacement and removal behavior outside this fix.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@StephaneDelcroix StephaneDelcroix changed the title Fix SourceGen Hot Reload updates to resource dictionaries and implicit styles Fix resource additions in SourceGen Hot Reload Nov 2, 2026
@sheiksyedm
sheiksyedm requested review from kubaflo and removed request for kubaflo November 2, 2026 13:28
@StephaneDelcroix
StephaneDelcroix marked this pull request as ready for review November 2, 2026 14:15
@StephaneDelcroix
StephaneDelcroix requested review from dalexsoto and kubaflo and a balanced review from Copilot and removed request for Copilot November 2, 2026 14:15
@kubaflo

This comment has been minimized.

@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 Nov 2, 2026
@azure-pipelines

This comment has been minimized.

@MauiBot

This comment has been minimized.

@MauiBot MauiBot added the s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) label Nov 2, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

child.IgnorablePrefixes = child.IgnorablePrefixes?.ToList();
}), dictionary);
node.Accept(new ExpandMarkupsVisitor(context), dictionary);
node.Accept(new PruneIgnoredNodesVisitor(false), dictionary);
using var implicitStyleGuard = key == null ? PrePost.NewBlock(codeWriter) : PrePost.NoBlock();
if (node.IsLazyResource(dictionary, context))
{
SetPropertyHelpers.AddLazyResourceToResourceDictionary(codeWriter, context.Variables[dictionary], node, context, useLocalFactory: true);
Comment on lines +1552 to +1554
codeWriter.WriteLine($"if ((object?){entry.Value.ValueAccessor} is not null)");
codeWriter.Indent++;
codeWriter.WriteLine($"global::Microsoft.Maui.Controls.Xaml.XamlComponentRegistry.Register(this, \"{EscapeString(id)}\", {entry.Value.ValueAccessor});");
@MauiBot

This comment has been minimized.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Nov 6, 2026
@kubaflo

This comment has been minimized.

@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 Nov 6, 2026
@azure-pipelines

This comment has been minimized.

@MauiBot

MauiBot commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator

PR Test Gate

@StephaneDelcroix — existing-test verification for commit 245e6a45.

Result PASSED Platform Android Commit 245e6a45


🧪 Gate analysis — click to expand

✅ Passed. The selected verification satisfied the gate's passing conditions. Unmatched, skipped, or inconclusive groups are not passing evidence.

🧪 Unit tests
Test group Without fix With fix
Maui37888Tests ⚠ Passed without the fix (113s) ✅ Passed (25s)
NestedControlHotReloadTests ✅ Failed as expected (20s) ✅ Passed (18s)
XamlIncrementalHotReloadPipelineTests ✅ Failed as expected (22s) ✅ Passed (20s)
Execution log excerpts

Without fix Maui37888Tests

d Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedResourcePreservesIgnorableContext [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedResourceReferencesRetainedExplicitSubtree [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedResourcePreservesLazySharedSemantics [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedNamedResourceRegistersLiveNameAndCompatibleField [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedImplicitResourceIsRemovedInFollowingGeneration [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedEagerResourcesResolveForwardReferences [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedResourceResolvesOuterBindingAtRuntime [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.ApplicationResourceUpdate_ReachesExistingAndNewConsumers [1 ms]
  Passed Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.NullConvertedResource_GuardsComponentRegistration [136 ms]
Test Run Successful.
Total tests: 19
     Passed: 5
    Skipped: 14
 Total time: 5.2158 Seconds

With fix Maui37888Tests

d Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedResourcePreservesIgnorableContext [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedResourceReferencesRetainedExplicitSubtree [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedResourcePreservesLazySharedSemantics [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedNamedResourceRegistersLiveNameAndCompatibleField [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedImplicitResourceIsRemovedInFollowingGeneration [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedEagerResourcesResolveForwardReferences [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.AddedResourceResolvesOuterBindingAtRuntime [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.ApplicationResourceUpdate_ReachesExistingAndNewConsumers [1 ms]
  Passed Microsoft.Maui.Controls.SourceGen.UnitTests.Maui37888Tests.NullConvertedResource_GuardsComponentRegistration [138 ms]
Test Run Successful.
Total tests: 19
     Passed: 5
    Skipped: 14
 Total time: 6.5767 Seconds

Without fix NestedControlHotReloadTests

     at Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.AiAssisted.NestedControlHotReloadTests.NestedGeneratedRoots_LocalResources_EmitsGuardedResourceAddition() in /_/src/Controls/tests/SourceGen.UnitTests/HotReload/AiAssisted/NestedControlHotReloadTests.GeneratedRoots.cs:line 30
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)

With fix NestedControlHotReloadTests

t.net 00:00:05.58]       Requires runtime support for applying metadata updates. Set DOTNET_MODIFIABLE_ASSEMBLIES=debug in the environment to run these tests.
[xUnit.net 00:00:05.59]     Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.AiAssisted.NestedControlHotReloadTests.NestedControls_LocalResources_XReference_RebindIndependently [SKIP]
[xUnit.net 00:00:05.59]       Requires runtime support for applying metadata updates. Set DOTNET_MODIFIABLE_ASSEMBLIES=debug in the environment to run these tests.
[xUnit.net 00:00:05.87]   Finished:    Microsoft.Maui.Controls.SourceGen.UnitTests
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.AiAssisted.NestedControlHotReloadTests.NestedCustomControls_Construct_HaveIndependentIdentityAndNamescope [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.AiAssisted.NestedControlHotReloadTests.NestedControls_LocalResources_XReference_RebindIndependently [1 ms]
  Passed Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.AiAssisted.NestedControlHotReloadTests.NestedLocalResources_CustomConverter_EmitsSkipMarker [300 ms]
Test Run Successful.
Total tests: 4
     Passed: 2
    Skipped: 2
 Total time: 7.0144 Seconds

PR head: 245e6a45.

Without-fix baseline: e6abee71.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Nov 6, 2026

@github-actions github-actions Bot 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.

Expert Review — 3 findings

Reviewed commit 245e6a4.

See inline comments for details.

continue;
if (clonedIds.TryGetValue(element, out var id) && id.Length != 0)
{
codeWriter.WriteLine($"if ((object?){entry.Value.ValueAccessor} is not null)");

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.

[major] Logic and Correctness Verification - Adding a named Style with a literal setter such as <Setter Property="TextColor" Value="Red" /> generates invalid UpdateComponent code. CreateValuesVisitor records an empty ValueAccessor placeholder for inlineable setters, but this prepass registers it before SetPropertiesVisitor materializes it, emitting if ((object?) is not null) and a Register call with a missing argument. Defer placeholder component registration until materialization while preserving early live-name registration for forward references. Add a compilation regression with a literal setter; the eager-style collision fixture uses an element-valued setter and misses this case.

using var implicitStyleGuard = key == null ? PrePost.NewBlock(codeWriter) : PrePost.NoBlock();
if (node.IsLazyResource(dictionary, context))
{
SetPropertyHelpers.AddLazyResourceToResourceDictionary(codeWriter, context.Variables[dictionary], node, context, useLocalFactory: true);

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.

[major] Logic and Correctness Verification - Adding an eager x:String keyed Caption followed by an implicit Label style whose Text setter uses {StaticResource Caption} fails when an existing Label consumes the style. Caption is inserted only by the queued eager initializer, but AddFactory immediately notifies the existing consumer and realizes the style before Caption exists. Runtime StaticResource resolution then throws, or reports a missing resource and leaves degraded styling when an exception collector is installed. Queue factory registration in resource order alongside eager initialization, preserving the live-name prepass. The application fixture adds independent resources and does not cover this dependency.

child.IgnorablePrefixes = child.IgnorablePrefixes?.ToList();
}), dictionary);
node.Accept(new ExpandMarkupsVisitor(context), dictionary);
node.Accept(new PruneIgnoredNodesVisitor(false), dictionary);

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.

[major] Logic and Correctness Verification - Adding an ignored resource element still reaches inflation. Under inherited mc:Ignorable="d", adding <d:Token x:Key="Preview" /> with d mapped to a resolvable CLR Token type should have no runtime effect. Pruning the resource directly clears its contents but never removes it from dictionary.CollectionItems, so emission constructs Token and inserts it under the key captured before pruning. An unresolved ignored type instead leaves no variable and fails generation. Prune through the synthetic dictionary and skip emission when its child is removed. The ignore-context fixtures cover ignored attributes, not ignored resource elements.

@kubaflo

This comment has been minimized.

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Tests Failure Analysis

@StephaneDelcroix — test-failure analysis for commit 245e6a4.

Scope CI failures Commit 245e6a4


🧪 CI Analysis — click to expand
📊 maui-pr

No failures found.


🧪 maui-pr-devicetests

Insufficient data — Nine completed Helix jobs report zero failed work items, but individual test/fixture outcomes were not captured; exit codes alone cannot verify passing tests.


🧪 maui-pr-uitests

🧭 Follow-up — actions and refresh

Next action: Restore complete UI diagnostics and device test outcomes; compare unresolved failures individually with equivalent target configurations.

Maintainers: comment /review tests to refresh this report.

@kubaflo
kubaflo changed the base branch from main to candidate/11.0.1xx-sr2 November 11, 2026 21:57
@kubaflo
kubaflo merged commit 910b480 into dotnet:candidate/11.0.1xx-sr2 Nov 11, 2026
135 of 176 checks passed
kubaflo added a commit that referenced this pull request Nov 13, 2026
<!-- 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!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Fix source-generated incremental XAML Hot Reload resource additions.
Adding an implicit `Label` style in `App.xaml` or a merged `Styles.xaml`
now updates existing labels through the normal resource-change
notifications.

The update writer skipped implicit styles because they have no explicit
`x:Key`, treated explicit `ResourceDictionary` containers as resource
values, and routed dictionary-root child additions through the generic
content-property path.

The new addition paths reuse the normal inflation visitors and existing
resource dictionary APIs: `Add` for eager resources and `AddFactory` for
lazy resources, including implicit styles. Existing keys are guarded so
these additions do not replace existing resources. Existing merged
dictionaries, application-added resources, and live controls remain in
place. Guards apply before constructing eager implicit styles as well as
before registering lazy factories.

Added resources retain the normal lazy and `x:Shared` behavior,
inherited `x:DataType`, and outer `x:Reference` bindings. Retained named
elements are resolved through the live namescope (including explicit
Content/Resources subtrees), and added eager named resources register
their live names, compatible fields, and component IDs. Ancestor
data-type context is cloned and normalized, including
`x:DataType="{x:Type local:Person}"`, without mutating the cached tree.
Top-level keyed `OnPlatform<T>` additions are simplified through their
synthetic dictionary parent so the selected platform value is inflated.

Resource-local and inherited `mc:Ignorable` declarations and
ignore-prefix lists are preserved and normalized on cloned context.
Pruning receives the synthetic dictionary parent, preventing generator
crashes and runtime design-time property assignments. Added eager
resources are created and registered before reference-dependent
properties are initialized, allowing forward `x:Reference` between
resources added in the same update. Live-name and compatible-field
assignment also covers non-Element resources; dictionary-root field
assignment is independent of the Element-only namescope and StyleId
handling.

Addition-only implicit resource containers use guarded inflation rather
than reconstructing unchanged resources; retained keyless class styles
do not disqualify this path. Successfully inserted keyed resources merge
into the existing resource-key bookkeeping so subsequent implicit
removals keep working, without claiming keys that already existed at
runtime. Other implicit update/removal edits keep the existing path. Hot
Reload factories and deferred initializers, including nested resource
factories, use local functions with explicit delegates to avoid
introducing compiler-cached lambda fields during metadata updates. Names
in separate template/style scopes are excluded from the outer reference
map and live field assignment.

This revision removes the earlier Core, runtime registry, public API,
ownership-snapshot, and binding-subscription changes. Production changes
are confined to the source generator's update writer,
patch-input/context plumbing, and directly related
comparison/resource-factory helpers. It does not add general resource
replacement/removal reconciliation or change ordinary runtime resource
behavior.

Targets **`main`**. Broader resource-update and
collection-reconciliation cases are outside this PR's scope.

**Validation**

Latest review follow-up, commit `17b1d8c04e`, using the worktree's .NET
11 RC2 SDK and repository-absolute project paths:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --verbosity quiet
```

Passed: **708**, failed: **0**, skipped: **0**.

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~Maui37888Tests --verbosity quiet
```

Passed: **43**, failed: **0**, skipped: **0**.

The expanded regressions reproduced the new failures before the fixes:
resource-local and inherited ignore-prefix handling, forward references
between eager additions, non-Element named-resource assignment, retained
class-style preservation, and add-B/replace-with-C implicit resource
bookkeeping. Collision regressions prepopulate the exact incoming
keyed-resource or implicit-style key with a runtime factory, assert no
factory realization or incoming construction during the update, and
verify preservation through the following removal edit. Both implicit
and explicit containers are covered, including eager and lazy implicit
styles. Named dictionary-root cases exercise the SourceGen-only
configuration: diagnostics/runtime fallback is disabled because the
pre-existing fallback emits Element-only name lookups for dictionary
roots.

Earlier follow-up regressions independently reproduced all five prior
review findings before their fixes: null references to retained explicit
subtrees, `OnPlatform<Color>` wrappers instead of selected colors,
missing live names for added named resources, CS0103 for inherited
`x:Type` data-type context, and unexpected existing-resource
construction in implicit containers. Tests cover lazy/eager references,
compatible named fields and chained additions, Android/iOS/MacCatalyst
target-framework selection (including a dictionary root), configured
resource identity/construction counts, and template/style scope
isolation. Exercising nested resources followed by another addition also
exposed a metadata-update crash; propagating the local-function factory
form to nested additions fixes it.

The full suite includes real metadata-update cases for implicit and
explicit App.xaml resource containers and a classless merged Styles.xaml
dictionary. These verify existing/new consumers, keyed additions, and
preservation of existing resources and controls. In the earlier worktree
(`repo=/Users/sde/Projects/Microsoft/maui-pr-39826`), the following
focused command reproduced all **3 failures** before the generator fix,
with an unchanged null background instead of red; all three pass in the
latest full-suite run:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$repo/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~AddingApplicationResources_UpdatesExistingAndNewConsumers --logger 'console;verbosity=normal'
```

Formatted changed C# files with the repository settings:

```bash
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs --verbosity quiet
```

Passed. `git diff --check` also passed. Native device/IDE validation was
not run. Existing device/UI CI failures remain untriaged. No check runs
or commit-status entries were available for the newly pushed head when
checked. The earlier hosted test gate skipped metadata-update cases, so
its result is not evidence that these runtime cases executed.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Partially addresses #36732: resource additions, including implicit
styles.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 16, 2026
<!-- 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!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Fix source-generated incremental XAML Hot Reload resource additions.
Adding an implicit `Label` style in `App.xaml` or a merged `Styles.xaml`
now updates existing labels through the normal resource-change
notifications.

The update writer skipped implicit styles because they have no explicit
`x:Key`, treated explicit `ResourceDictionary` containers as resource
values, and routed dictionary-root child additions through the generic
content-property path.

The new addition paths reuse the normal inflation visitors and existing
resource dictionary APIs: `Add` for eager resources and `AddFactory` for
lazy resources, including implicit styles. Existing keys are guarded so
these additions do not replace existing resources. Existing merged
dictionaries, application-added resources, and live controls remain in
place. Guards apply before constructing eager implicit styles as well as
before registering lazy factories.

Added resources retain the normal lazy and `x:Shared` behavior,
inherited `x:DataType`, and outer `x:Reference` bindings. Retained named
elements are resolved through the live namescope (including explicit
Content/Resources subtrees), and added eager named resources register
their live names, compatible fields, and component IDs. Ancestor
data-type context is cloned and normalized, including
`x:DataType="{x:Type local:Person}"`, without mutating the cached tree.
Top-level keyed `OnPlatform<T>` additions are simplified through their
synthetic dictionary parent so the selected platform value is inflated.

Resource-local and inherited `mc:Ignorable` declarations and
ignore-prefix lists are preserved and normalized on cloned context.
Pruning receives the synthetic dictionary parent, preventing generator
crashes and runtime design-time property assignments. Added eager
resources are created and registered before reference-dependent
properties are initialized, allowing forward `x:Reference` between
resources added in the same update. Live-name and compatible-field
assignment also covers non-Element resources; dictionary-root field
assignment is independent of the Element-only namescope and StyleId
handling.

Addition-only implicit resource containers use guarded inflation rather
than reconstructing unchanged resources; retained keyless class styles
do not disqualify this path. Successfully inserted keyed resources merge
into the existing resource-key bookkeeping so subsequent implicit
removals keep working, without claiming keys that already existed at
runtime. Other implicit update/removal edits keep the existing path. Hot
Reload factories and deferred initializers, including nested resource
factories, use local functions with explicit delegates to avoid
introducing compiler-cached lambda fields during metadata updates. Names
in separate template/style scopes are excluded from the outer reference
map and live field assignment.

This revision removes the earlier Core, runtime registry, public API,
ownership-snapshot, and binding-subscription changes. Production changes
are confined to the source generator's update writer,
patch-input/context plumbing, and directly related
comparison/resource-factory helpers. It does not add general resource
replacement/removal reconciliation or change ordinary runtime resource
behavior.

Targets **`main`**. Broader resource-update and
collection-reconciliation cases are outside this PR's scope.

**Validation**

Latest review follow-up, commit `17b1d8c04e`, using the worktree's .NET
11 RC2 SDK and repository-absolute project paths:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --verbosity quiet
```

Passed: **708**, failed: **0**, skipped: **0**.

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~Maui37888Tests --verbosity quiet
```

Passed: **43**, failed: **0**, skipped: **0**.

The expanded regressions reproduced the new failures before the fixes:
resource-local and inherited ignore-prefix handling, forward references
between eager additions, non-Element named-resource assignment, retained
class-style preservation, and add-B/replace-with-C implicit resource
bookkeeping. Collision regressions prepopulate the exact incoming
keyed-resource or implicit-style key with a runtime factory, assert no
factory realization or incoming construction during the update, and
verify preservation through the following removal edit. Both implicit
and explicit containers are covered, including eager and lazy implicit
styles. Named dictionary-root cases exercise the SourceGen-only
configuration: diagnostics/runtime fallback is disabled because the
pre-existing fallback emits Element-only name lookups for dictionary
roots.

Earlier follow-up regressions independently reproduced all five prior
review findings before their fixes: null references to retained explicit
subtrees, `OnPlatform<Color>` wrappers instead of selected colors,
missing live names for added named resources, CS0103 for inherited
`x:Type` data-type context, and unexpected existing-resource
construction in implicit containers. Tests cover lazy/eager references,
compatible named fields and chained additions, Android/iOS/MacCatalyst
target-framework selection (including a dictionary root), configured
resource identity/construction counts, and template/style scope
isolation. Exercising nested resources followed by another addition also
exposed a metadata-update crash; propagating the local-function factory
form to nested additions fixes it.

The full suite includes real metadata-update cases for implicit and
explicit App.xaml resource containers and a classless merged Styles.xaml
dictionary. These verify existing/new consumers, keyed additions, and
preservation of existing resources and controls. In the earlier worktree
(`repo=/Users/sde/Projects/Microsoft/maui-pr-39826`), the following
focused command reproduced all **3 failures** before the generator fix,
with an unchanged null background instead of red; all three pass in the
latest full-suite run:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$repo/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~AddingApplicationResources_UpdatesExistingAndNewConsumers --logger 'console;verbosity=normal'
```

Formatted changed C# files with the repository settings:

```bash
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs --verbosity quiet
```

Passed. `git diff --check` also passed. Native device/IDE validation was
not run. Existing device/UI CI failures remain untriaged. No check runs
or commit-status entries were available for the newly pushed head when
checked. The earlier hosted test gate skipped metadata-update cases, so
its result is not evidence that these runtime cases executed.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Partially addresses #36732: resource additions, including implicit
styles.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 16, 2026
<!-- 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!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Fix source-generated incremental XAML Hot Reload resource additions.
Adding an implicit `Label` style in `App.xaml` or a merged `Styles.xaml`
now updates existing labels through the normal resource-change
notifications.

The update writer skipped implicit styles because they have no explicit
`x:Key`, treated explicit `ResourceDictionary` containers as resource
values, and routed dictionary-root child additions through the generic
content-property path.

The new addition paths reuse the normal inflation visitors and existing
resource dictionary APIs: `Add` for eager resources and `AddFactory` for
lazy resources, including implicit styles. Existing keys are guarded so
these additions do not replace existing resources. Existing merged
dictionaries, application-added resources, and live controls remain in
place. Guards apply before constructing eager implicit styles as well as
before registering lazy factories.

Added resources retain the normal lazy and `x:Shared` behavior,
inherited `x:DataType`, and outer `x:Reference` bindings. Retained named
elements are resolved through the live namescope (including explicit
Content/Resources subtrees), and added eager named resources register
their live names, compatible fields, and component IDs. Ancestor
data-type context is cloned and normalized, including
`x:DataType="{x:Type local:Person}"`, without mutating the cached tree.
Top-level keyed `OnPlatform<T>` additions are simplified through their
synthetic dictionary parent so the selected platform value is inflated.

Resource-local and inherited `mc:Ignorable` declarations and
ignore-prefix lists are preserved and normalized on cloned context.
Pruning receives the synthetic dictionary parent, preventing generator
crashes and runtime design-time property assignments. Added eager
resources are created and registered before reference-dependent
properties are initialized, allowing forward `x:Reference` between
resources added in the same update. Live-name and compatible-field
assignment also covers non-Element resources; dictionary-root field
assignment is independent of the Element-only namescope and StyleId
handling.

Addition-only implicit resource containers use guarded inflation rather
than reconstructing unchanged resources; retained keyless class styles
do not disqualify this path. Successfully inserted keyed resources merge
into the existing resource-key bookkeeping so subsequent implicit
removals keep working, without claiming keys that already existed at
runtime. Other implicit update/removal edits keep the existing path. Hot
Reload factories and deferred initializers, including nested resource
factories, use local functions with explicit delegates to avoid
introducing compiler-cached lambda fields during metadata updates. Names
in separate template/style scopes are excluded from the outer reference
map and live field assignment.

This revision removes the earlier Core, runtime registry, public API,
ownership-snapshot, and binding-subscription changes. Production changes
are confined to the source generator's update writer,
patch-input/context plumbing, and directly related
comparison/resource-factory helpers. It does not add general resource
replacement/removal reconciliation or change ordinary runtime resource
behavior.

Targets **`main`**. Broader resource-update and
collection-reconciliation cases are outside this PR's scope.

**Validation**

Latest review follow-up, commit `17b1d8c04e`, using the worktree's .NET
11 RC2 SDK and repository-absolute project paths:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --verbosity quiet
```

Passed: **708**, failed: **0**, skipped: **0**.

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~Maui37888Tests --verbosity quiet
```

Passed: **43**, failed: **0**, skipped: **0**.

The expanded regressions reproduced the new failures before the fixes:
resource-local and inherited ignore-prefix handling, forward references
between eager additions, non-Element named-resource assignment, retained
class-style preservation, and add-B/replace-with-C implicit resource
bookkeeping. Collision regressions prepopulate the exact incoming
keyed-resource or implicit-style key with a runtime factory, assert no
factory realization or incoming construction during the update, and
verify preservation through the following removal edit. Both implicit
and explicit containers are covered, including eager and lazy implicit
styles. Named dictionary-root cases exercise the SourceGen-only
configuration: diagnostics/runtime fallback is disabled because the
pre-existing fallback emits Element-only name lookups for dictionary
roots.

Earlier follow-up regressions independently reproduced all five prior
review findings before their fixes: null references to retained explicit
subtrees, `OnPlatform<Color>` wrappers instead of selected colors,
missing live names for added named resources, CS0103 for inherited
`x:Type` data-type context, and unexpected existing-resource
construction in implicit containers. Tests cover lazy/eager references,
compatible named fields and chained additions, Android/iOS/MacCatalyst
target-framework selection (including a dictionary root), configured
resource identity/construction counts, and template/style scope
isolation. Exercising nested resources followed by another addition also
exposed a metadata-update crash; propagating the local-function factory
form to nested additions fixes it.

The full suite includes real metadata-update cases for implicit and
explicit App.xaml resource containers and a classless merged Styles.xaml
dictionary. These verify existing/new consumers, keyed additions, and
preservation of existing resources and controls. In the earlier worktree
(`repo=/Users/sde/Projects/Microsoft/maui-pr-39826`), the following
focused command reproduced all **3 failures** before the generator fix,
with an unchanged null background instead of red; all three pass in the
latest full-suite run:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$repo/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~AddingApplicationResources_UpdatesExistingAndNewConsumers --logger 'console;verbosity=normal'
```

Formatted changed C# files with the repository settings:

```bash
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs --verbosity quiet
```

Passed. `git diff --check` also passed. Native device/IDE validation was
not run. Existing device/UI CI failures remain untriaged. No check runs
or commit-status entries were available for the newly pushed head when
checked. The earlier hosted test gate skipped metadata-update cases, so
its result is not evidence that these runtime cases executed.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Partially addresses #36732: resource additions, including implicit
styles.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 17, 2026
<!-- 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!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Fix source-generated incremental XAML Hot Reload resource additions.
Adding an implicit `Label` style in `App.xaml` or a merged `Styles.xaml`
now updates existing labels through the normal resource-change
notifications.

The update writer skipped implicit styles because they have no explicit
`x:Key`, treated explicit `ResourceDictionary` containers as resource
values, and routed dictionary-root child additions through the generic
content-property path.

The new addition paths reuse the normal inflation visitors and existing
resource dictionary APIs: `Add` for eager resources and `AddFactory` for
lazy resources, including implicit styles. Existing keys are guarded so
these additions do not replace existing resources. Existing merged
dictionaries, application-added resources, and live controls remain in
place. Guards apply before constructing eager implicit styles as well as
before registering lazy factories.

Added resources retain the normal lazy and `x:Shared` behavior,
inherited `x:DataType`, and outer `x:Reference` bindings. Retained named
elements are resolved through the live namescope (including explicit
Content/Resources subtrees), and added eager named resources register
their live names, compatible fields, and component IDs. Ancestor
data-type context is cloned and normalized, including
`x:DataType="{x:Type local:Person}"`, without mutating the cached tree.
Top-level keyed `OnPlatform<T>` additions are simplified through their
synthetic dictionary parent so the selected platform value is inflated.

Resource-local and inherited `mc:Ignorable` declarations and
ignore-prefix lists are preserved and normalized on cloned context.
Pruning receives the synthetic dictionary parent, preventing generator
crashes and runtime design-time property assignments. Added eager
resources are created and registered before reference-dependent
properties are initialized, allowing forward `x:Reference` between
resources added in the same update. Live-name and compatible-field
assignment also covers non-Element resources; dictionary-root field
assignment is independent of the Element-only namescope and StyleId
handling.

Addition-only implicit resource containers use guarded inflation rather
than reconstructing unchanged resources; retained keyless class styles
do not disqualify this path. Successfully inserted keyed resources merge
into the existing resource-key bookkeeping so subsequent implicit
removals keep working, without claiming keys that already existed at
runtime. Other implicit update/removal edits keep the existing path. Hot
Reload factories and deferred initializers, including nested resource
factories, use local functions with explicit delegates to avoid
introducing compiler-cached lambda fields during metadata updates. Names
in separate template/style scopes are excluded from the outer reference
map and live field assignment.

This revision removes the earlier Core, runtime registry, public API,
ownership-snapshot, and binding-subscription changes. Production changes
are confined to the source generator's update writer,
patch-input/context plumbing, and directly related
comparison/resource-factory helpers. It does not add general resource
replacement/removal reconciliation or change ordinary runtime resource
behavior.

Targets **`main`**. Broader resource-update and
collection-reconciliation cases are outside this PR's scope.

**Validation**

Latest review follow-up, commit `17b1d8c04e`, using the worktree's .NET
11 RC2 SDK and repository-absolute project paths:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --verbosity quiet
```

Passed: **708**, failed: **0**, skipped: **0**.

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~Maui37888Tests --verbosity quiet
```

Passed: **43**, failed: **0**, skipped: **0**.

The expanded regressions reproduced the new failures before the fixes:
resource-local and inherited ignore-prefix handling, forward references
between eager additions, non-Element named-resource assignment, retained
class-style preservation, and add-B/replace-with-C implicit resource
bookkeeping. Collision regressions prepopulate the exact incoming
keyed-resource or implicit-style key with a runtime factory, assert no
factory realization or incoming construction during the update, and
verify preservation through the following removal edit. Both implicit
and explicit containers are covered, including eager and lazy implicit
styles. Named dictionary-root cases exercise the SourceGen-only
configuration: diagnostics/runtime fallback is disabled because the
pre-existing fallback emits Element-only name lookups for dictionary
roots.

Earlier follow-up regressions independently reproduced all five prior
review findings before their fixes: null references to retained explicit
subtrees, `OnPlatform<Color>` wrappers instead of selected colors,
missing live names for added named resources, CS0103 for inherited
`x:Type` data-type context, and unexpected existing-resource
construction in implicit containers. Tests cover lazy/eager references,
compatible named fields and chained additions, Android/iOS/MacCatalyst
target-framework selection (including a dictionary root), configured
resource identity/construction counts, and template/style scope
isolation. Exercising nested resources followed by another addition also
exposed a metadata-update crash; propagating the local-function factory
form to nested additions fixes it.

The full suite includes real metadata-update cases for implicit and
explicit App.xaml resource containers and a classless merged Styles.xaml
dictionary. These verify existing/new consumers, keyed additions, and
preservation of existing resources and controls. In the earlier worktree
(`repo=/Users/sde/Projects/Microsoft/maui-pr-39826`), the following
focused command reproduced all **3 failures** before the generator fix,
with an unchanged null background instead of red; all three pass in the
latest full-suite run:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$repo/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~AddingApplicationResources_UpdatesExistingAndNewConsumers --logger 'console;verbosity=normal'
```

Formatted changed C# files with the repository settings:

```bash
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs --verbosity quiet
```

Passed. `git diff --check` also passed. Native device/IDE validation was
not run. Existing device/UI CI failures remain untriaged. No check runs
or commit-status entries were available for the newly pushed head when
checked. The earlier hosted test gate skipped metadata-update cases, so
its result is not evidence that these runtime cases executed.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Partially addresses #36732: resource additions, including implicit
styles.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 18, 2026
<!-- 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!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Fix source-generated incremental XAML Hot Reload resource additions.
Adding an implicit `Label` style in `App.xaml` or a merged `Styles.xaml`
now updates existing labels through the normal resource-change
notifications.

The update writer skipped implicit styles because they have no explicit
`x:Key`, treated explicit `ResourceDictionary` containers as resource
values, and routed dictionary-root child additions through the generic
content-property path.

The new addition paths reuse the normal inflation visitors and existing
resource dictionary APIs: `Add` for eager resources and `AddFactory` for
lazy resources, including implicit styles. Existing keys are guarded so
these additions do not replace existing resources. Existing merged
dictionaries, application-added resources, and live controls remain in
place. Guards apply before constructing eager implicit styles as well as
before registering lazy factories.

Added resources retain the normal lazy and `x:Shared` behavior,
inherited `x:DataType`, and outer `x:Reference` bindings. Retained named
elements are resolved through the live namescope (including explicit
Content/Resources subtrees), and added eager named resources register
their live names, compatible fields, and component IDs. Ancestor
data-type context is cloned and normalized, including
`x:DataType="{x:Type local:Person}"`, without mutating the cached tree.
Top-level keyed `OnPlatform<T>` additions are simplified through their
synthetic dictionary parent so the selected platform value is inflated.

Resource-local and inherited `mc:Ignorable` declarations and
ignore-prefix lists are preserved and normalized on cloned context.
Pruning receives the synthetic dictionary parent, preventing generator
crashes and runtime design-time property assignments. Added eager
resources are created and registered before reference-dependent
properties are initialized, allowing forward `x:Reference` between
resources added in the same update. Live-name and compatible-field
assignment also covers non-Element resources; dictionary-root field
assignment is independent of the Element-only namescope and StyleId
handling.

Addition-only implicit resource containers use guarded inflation rather
than reconstructing unchanged resources; retained keyless class styles
do not disqualify this path. Successfully inserted keyed resources merge
into the existing resource-key bookkeeping so subsequent implicit
removals keep working, without claiming keys that already existed at
runtime. Other implicit update/removal edits keep the existing path. Hot
Reload factories and deferred initializers, including nested resource
factories, use local functions with explicit delegates to avoid
introducing compiler-cached lambda fields during metadata updates. Names
in separate template/style scopes are excluded from the outer reference
map and live field assignment.

This revision removes the earlier Core, runtime registry, public API,
ownership-snapshot, and binding-subscription changes. Production changes
are confined to the source generator's update writer,
patch-input/context plumbing, and directly related
comparison/resource-factory helpers. It does not add general resource
replacement/removal reconciliation or change ordinary runtime resource
behavior.

Targets **`main`**. Broader resource-update and
collection-reconciliation cases are outside this PR's scope.

**Validation**

Latest review follow-up, commit `17b1d8c04e`, using the worktree's .NET
11 RC2 SDK and repository-absolute project paths:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --verbosity quiet
```

Passed: **708**, failed: **0**, skipped: **0**.

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~Maui37888Tests --verbosity quiet
```

Passed: **43**, failed: **0**, skipped: **0**.

The expanded regressions reproduced the new failures before the fixes:
resource-local and inherited ignore-prefix handling, forward references
between eager additions, non-Element named-resource assignment, retained
class-style preservation, and add-B/replace-with-C implicit resource
bookkeeping. Collision regressions prepopulate the exact incoming
keyed-resource or implicit-style key with a runtime factory, assert no
factory realization or incoming construction during the update, and
verify preservation through the following removal edit. Both implicit
and explicit containers are covered, including eager and lazy implicit
styles. Named dictionary-root cases exercise the SourceGen-only
configuration: diagnostics/runtime fallback is disabled because the
pre-existing fallback emits Element-only name lookups for dictionary
roots.

Earlier follow-up regressions independently reproduced all five prior
review findings before their fixes: null references to retained explicit
subtrees, `OnPlatform<Color>` wrappers instead of selected colors,
missing live names for added named resources, CS0103 for inherited
`x:Type` data-type context, and unexpected existing-resource
construction in implicit containers. Tests cover lazy/eager references,
compatible named fields and chained additions, Android/iOS/MacCatalyst
target-framework selection (including a dictionary root), configured
resource identity/construction counts, and template/style scope
isolation. Exercising nested resources followed by another addition also
exposed a metadata-update crash; propagating the local-function factory
form to nested additions fixes it.

The full suite includes real metadata-update cases for implicit and
explicit App.xaml resource containers and a classless merged Styles.xaml
dictionary. These verify existing/new consumers, keyed additions, and
preservation of existing resources and controls. In the earlier worktree
(`repo=/Users/sde/Projects/Microsoft/maui-pr-39826`), the following
focused command reproduced all **3 failures** before the generator fix,
with an unchanged null background instead of red; all three pass in the
latest full-suite run:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$repo/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~AddingApplicationResources_UpdatesExistingAndNewConsumers --logger 'console;verbosity=normal'
```

Formatted changed C# files with the repository settings:

```bash
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs --verbosity quiet
```

Passed. `git diff --check` also passed. Native device/IDE validation was
not run. Existing device/UI CI failures remain untriaged. No check runs
or commit-status entries were available for the newly pushed head when
checked. The earlier hosted test gate skipped metadata-update cases, so
its result is not evidence that these runtime cases executed.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Partially addresses #36732: resource additions, including implicit
styles.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 18, 2026
<!-- 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!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Fix source-generated incremental XAML Hot Reload resource additions.
Adding an implicit `Label` style in `App.xaml` or a merged `Styles.xaml`
now updates existing labels through the normal resource-change
notifications.

The update writer skipped implicit styles because they have no explicit
`x:Key`, treated explicit `ResourceDictionary` containers as resource
values, and routed dictionary-root child additions through the generic
content-property path.

The new addition paths reuse the normal inflation visitors and existing
resource dictionary APIs: `Add` for eager resources and `AddFactory` for
lazy resources, including implicit styles. Existing keys are guarded so
these additions do not replace existing resources. Existing merged
dictionaries, application-added resources, and live controls remain in
place. Guards apply before constructing eager implicit styles as well as
before registering lazy factories.

Added resources retain the normal lazy and `x:Shared` behavior,
inherited `x:DataType`, and outer `x:Reference` bindings. Retained named
elements are resolved through the live namescope (including explicit
Content/Resources subtrees), and added eager named resources register
their live names, compatible fields, and component IDs. Ancestor
data-type context is cloned and normalized, including
`x:DataType="{x:Type local:Person}"`, without mutating the cached tree.
Top-level keyed `OnPlatform<T>` additions are simplified through their
synthetic dictionary parent so the selected platform value is inflated.

Resource-local and inherited `mc:Ignorable` declarations and
ignore-prefix lists are preserved and normalized on cloned context.
Pruning receives the synthetic dictionary parent, preventing generator
crashes and runtime design-time property assignments. Added eager
resources are created and registered before reference-dependent
properties are initialized, allowing forward `x:Reference` between
resources added in the same update. Live-name and compatible-field
assignment also covers non-Element resources; dictionary-root field
assignment is independent of the Element-only namescope and StyleId
handling.

Addition-only implicit resource containers use guarded inflation rather
than reconstructing unchanged resources; retained keyless class styles
do not disqualify this path. Successfully inserted keyed resources merge
into the existing resource-key bookkeeping so subsequent implicit
removals keep working, without claiming keys that already existed at
runtime. Other implicit update/removal edits keep the existing path. Hot
Reload factories and deferred initializers, including nested resource
factories, use local functions with explicit delegates to avoid
introducing compiler-cached lambda fields during metadata updates. Names
in separate template/style scopes are excluded from the outer reference
map and live field assignment.

This revision removes the earlier Core, runtime registry, public API,
ownership-snapshot, and binding-subscription changes. Production changes
are confined to the source generator's update writer,
patch-input/context plumbing, and directly related
comparison/resource-factory helpers. It does not add general resource
replacement/removal reconciliation or change ordinary runtime resource
behavior.

Targets **`main`**. Broader resource-update and
collection-reconciliation cases are outside this PR's scope.

**Validation**

Latest review follow-up, commit `17b1d8c04e`, using the worktree's .NET
11 RC2 SDK and repository-absolute project paths:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --verbosity quiet
```

Passed: **708**, failed: **0**, skipped: **0**.

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~Maui37888Tests --verbosity quiet
```

Passed: **43**, failed: **0**, skipped: **0**.

The expanded regressions reproduced the new failures before the fixes:
resource-local and inherited ignore-prefix handling, forward references
between eager additions, non-Element named-resource assignment, retained
class-style preservation, and add-B/replace-with-C implicit resource
bookkeeping. Collision regressions prepopulate the exact incoming
keyed-resource or implicit-style key with a runtime factory, assert no
factory realization or incoming construction during the update, and
verify preservation through the following removal edit. Both implicit
and explicit containers are covered, including eager and lazy implicit
styles. Named dictionary-root cases exercise the SourceGen-only
configuration: diagnostics/runtime fallback is disabled because the
pre-existing fallback emits Element-only name lookups for dictionary
roots.

Earlier follow-up regressions independently reproduced all five prior
review findings before their fixes: null references to retained explicit
subtrees, `OnPlatform<Color>` wrappers instead of selected colors,
missing live names for added named resources, CS0103 for inherited
`x:Type` data-type context, and unexpected existing-resource
construction in implicit containers. Tests cover lazy/eager references,
compatible named fields and chained additions, Android/iOS/MacCatalyst
target-framework selection (including a dictionary root), configured
resource identity/construction counts, and template/style scope
isolation. Exercising nested resources followed by another addition also
exposed a metadata-update crash; propagating the local-function factory
form to nested additions fixes it.

The full suite includes real metadata-update cases for implicit and
explicit App.xaml resource containers and a classless merged Styles.xaml
dictionary. These verify existing/new consumers, keyed additions, and
preservation of existing resources and controls. In the earlier worktree
(`repo=/Users/sde/Projects/Microsoft/maui-pr-39826`), the following
focused command reproduced all **3 failures** before the generator fix,
with an unchanged null background instead of red; all three pass in the
latest full-suite run:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$repo/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~AddingApplicationResources_UpdatesExistingAndNewConsumers --logger 'console;verbosity=normal'
```

Formatted changed C# files with the repository settings:

```bash
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs --verbosity quiet
```

Passed. `git diff --check` also passed. Native device/IDE validation was
not run. Existing device/UI CI failures remain untriaged. No check runs
or commit-status entries were available for the newly pushed head when
checked. The earlier hosted test gate skipped metadata-update cases, so
its result is not evidence that these runtime cases executed.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Partially addresses #36732: resource additions, including implicit
styles.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 18, 2026
<!-- 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!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Fix source-generated incremental XAML Hot Reload resource additions.
Adding an implicit `Label` style in `App.xaml` or a merged `Styles.xaml`
now updates existing labels through the normal resource-change
notifications.

The update writer skipped implicit styles because they have no explicit
`x:Key`, treated explicit `ResourceDictionary` containers as resource
values, and routed dictionary-root child additions through the generic
content-property path.

The new addition paths reuse the normal inflation visitors and existing
resource dictionary APIs: `Add` for eager resources and `AddFactory` for
lazy resources, including implicit styles. Existing keys are guarded so
these additions do not replace existing resources. Existing merged
dictionaries, application-added resources, and live controls remain in
place. Guards apply before constructing eager implicit styles as well as
before registering lazy factories.

Added resources retain the normal lazy and `x:Shared` behavior,
inherited `x:DataType`, and outer `x:Reference` bindings. Retained named
elements are resolved through the live namescope (including explicit
Content/Resources subtrees), and added eager named resources register
their live names, compatible fields, and component IDs. Ancestor
data-type context is cloned and normalized, including
`x:DataType="{x:Type local:Person}"`, without mutating the cached tree.
Top-level keyed `OnPlatform<T>` additions are simplified through their
synthetic dictionary parent so the selected platform value is inflated.

Resource-local and inherited `mc:Ignorable` declarations and
ignore-prefix lists are preserved and normalized on cloned context.
Pruning receives the synthetic dictionary parent, preventing generator
crashes and runtime design-time property assignments. Added eager
resources are created and registered before reference-dependent
properties are initialized, allowing forward `x:Reference` between
resources added in the same update. Live-name and compatible-field
assignment also covers non-Element resources; dictionary-root field
assignment is independent of the Element-only namescope and StyleId
handling.

Addition-only implicit resource containers use guarded inflation rather
than reconstructing unchanged resources; retained keyless class styles
do not disqualify this path. Successfully inserted keyed resources merge
into the existing resource-key bookkeeping so subsequent implicit
removals keep working, without claiming keys that already existed at
runtime. Other implicit update/removal edits keep the existing path. Hot
Reload factories and deferred initializers, including nested resource
factories, use local functions with explicit delegates to avoid
introducing compiler-cached lambda fields during metadata updates. Names
in separate template/style scopes are excluded from the outer reference
map and live field assignment.

This revision removes the earlier Core, runtime registry, public API,
ownership-snapshot, and binding-subscription changes. Production changes
are confined to the source generator's update writer,
patch-input/context plumbing, and directly related
comparison/resource-factory helpers. It does not add general resource
replacement/removal reconciliation or change ordinary runtime resource
behavior.

Targets **`main`**. Broader resource-update and
collection-reconciliation cases are outside this PR's scope.

**Validation**

Latest review follow-up, commit `17b1d8c04e`, using the worktree's .NET
11 RC2 SDK and repository-absolute project paths:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --verbosity quiet
```

Passed: **708**, failed: **0**, skipped: **0**.

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~Maui37888Tests --verbosity quiet
```

Passed: **43**, failed: **0**, skipped: **0**.

The expanded regressions reproduced the new failures before the fixes:
resource-local and inherited ignore-prefix handling, forward references
between eager additions, non-Element named-resource assignment, retained
class-style preservation, and add-B/replace-with-C implicit resource
bookkeeping. Collision regressions prepopulate the exact incoming
keyed-resource or implicit-style key with a runtime factory, assert no
factory realization or incoming construction during the update, and
verify preservation through the following removal edit. Both implicit
and explicit containers are covered, including eager and lazy implicit
styles. Named dictionary-root cases exercise the SourceGen-only
configuration: diagnostics/runtime fallback is disabled because the
pre-existing fallback emits Element-only name lookups for dictionary
roots.

Earlier follow-up regressions independently reproduced all five prior
review findings before their fixes: null references to retained explicit
subtrees, `OnPlatform<Color>` wrappers instead of selected colors,
missing live names for added named resources, CS0103 for inherited
`x:Type` data-type context, and unexpected existing-resource
construction in implicit containers. Tests cover lazy/eager references,
compatible named fields and chained additions, Android/iOS/MacCatalyst
target-framework selection (including a dictionary root), configured
resource identity/construction counts, and template/style scope
isolation. Exercising nested resources followed by another addition also
exposed a metadata-update crash; propagating the local-function factory
form to nested additions fixes it.

The full suite includes real metadata-update cases for implicit and
explicit App.xaml resource containers and a classless merged Styles.xaml
dictionary. These verify existing/new consumers, keyed additions, and
preservation of existing resources and controls. In the earlier worktree
(`repo=/Users/sde/Projects/Microsoft/maui-pr-39826`), the following
focused command reproduced all **3 failures** before the generator fix,
with an unchanged null background instead of red; all three pass in the
latest full-suite run:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$repo/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~AddingApplicationResources_UpdatesExistingAndNewConsumers --logger 'console;verbosity=normal'
```

Formatted changed C# files with the repository settings:

```bash
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs --verbosity quiet
```

Passed. `git diff --check` also passed. Native device/IDE validation was
not run. Existing device/UI CI failures remain untriaged. No check runs
or commit-status entries were available for the newly pushed head when
checked. The earlier hosted test gate skipped metadata-update cases, so
its result is not evidence that these runtime cases executed.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Partially addresses #36732: resource additions, including implicit
styles.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 19, 2026
<!-- 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!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Fix source-generated incremental XAML Hot Reload resource additions.
Adding an implicit `Label` style in `App.xaml` or a merged `Styles.xaml`
now updates existing labels through the normal resource-change
notifications.

The update writer skipped implicit styles because they have no explicit
`x:Key`, treated explicit `ResourceDictionary` containers as resource
values, and routed dictionary-root child additions through the generic
content-property path.

The new addition paths reuse the normal inflation visitors and existing
resource dictionary APIs: `Add` for eager resources and `AddFactory` for
lazy resources, including implicit styles. Existing keys are guarded so
these additions do not replace existing resources. Existing merged
dictionaries, application-added resources, and live controls remain in
place. Guards apply before constructing eager implicit styles as well as
before registering lazy factories.

Added resources retain the normal lazy and `x:Shared` behavior,
inherited `x:DataType`, and outer `x:Reference` bindings. Retained named
elements are resolved through the live namescope (including explicit
Content/Resources subtrees), and added eager named resources register
their live names, compatible fields, and component IDs. Ancestor
data-type context is cloned and normalized, including
`x:DataType="{x:Type local:Person}"`, without mutating the cached tree.
Top-level keyed `OnPlatform<T>` additions are simplified through their
synthetic dictionary parent so the selected platform value is inflated.

Resource-local and inherited `mc:Ignorable` declarations and
ignore-prefix lists are preserved and normalized on cloned context.
Pruning receives the synthetic dictionary parent, preventing generator
crashes and runtime design-time property assignments. Added eager
resources are created and registered before reference-dependent
properties are initialized, allowing forward `x:Reference` between
resources added in the same update. Live-name and compatible-field
assignment also covers non-Element resources; dictionary-root field
assignment is independent of the Element-only namescope and StyleId
handling.

Addition-only implicit resource containers use guarded inflation rather
than reconstructing unchanged resources; retained keyless class styles
do not disqualify this path. Successfully inserted keyed resources merge
into the existing resource-key bookkeeping so subsequent implicit
removals keep working, without claiming keys that already existed at
runtime. Other implicit update/removal edits keep the existing path. Hot
Reload factories and deferred initializers, including nested resource
factories, use local functions with explicit delegates to avoid
introducing compiler-cached lambda fields during metadata updates. Names
in separate template/style scopes are excluded from the outer reference
map and live field assignment.

This revision removes the earlier Core, runtime registry, public API,
ownership-snapshot, and binding-subscription changes. Production changes
are confined to the source generator's update writer,
patch-input/context plumbing, and directly related
comparison/resource-factory helpers. It does not add general resource
replacement/removal reconciliation or change ordinary runtime resource
behavior.

Targets **`main`**. Broader resource-update and
collection-reconciliation cases are outside this PR's scope.

**Validation**

Latest review follow-up, commit `17b1d8c04e`, using the worktree's .NET
11 RC2 SDK and repository-absolute project paths:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --verbosity quiet
```

Passed: **708**, failed: **0**, skipped: **0**.

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~Maui37888Tests --verbosity quiet
```

Passed: **43**, failed: **0**, skipped: **0**.

The expanded regressions reproduced the new failures before the fixes:
resource-local and inherited ignore-prefix handling, forward references
between eager additions, non-Element named-resource assignment, retained
class-style preservation, and add-B/replace-with-C implicit resource
bookkeeping. Collision regressions prepopulate the exact incoming
keyed-resource or implicit-style key with a runtime factory, assert no
factory realization or incoming construction during the update, and
verify preservation through the following removal edit. Both implicit
and explicit containers are covered, including eager and lazy implicit
styles. Named dictionary-root cases exercise the SourceGen-only
configuration: diagnostics/runtime fallback is disabled because the
pre-existing fallback emits Element-only name lookups for dictionary
roots.

Earlier follow-up regressions independently reproduced all five prior
review findings before their fixes: null references to retained explicit
subtrees, `OnPlatform<Color>` wrappers instead of selected colors,
missing live names for added named resources, CS0103 for inherited
`x:Type` data-type context, and unexpected existing-resource
construction in implicit containers. Tests cover lazy/eager references,
compatible named fields and chained additions, Android/iOS/MacCatalyst
target-framework selection (including a dictionary root), configured
resource identity/construction counts, and template/style scope
isolation. Exercising nested resources followed by another addition also
exposed a metadata-update crash; propagating the local-function factory
form to nested additions fixes it.

The full suite includes real metadata-update cases for implicit and
explicit App.xaml resource containers and a classless merged Styles.xaml
dictionary. These verify existing/new consumers, keyed additions, and
preservation of existing resources and controls. In the earlier worktree
(`repo=/Users/sde/Projects/Microsoft/maui-pr-39826`), the following
focused command reproduced all **3 failures** before the generator fix,
with an unchanged null background instead of red; all three pass in the
latest full-suite run:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$repo/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~AddingApplicationResources_UpdatesExistingAndNewConsumers --logger 'console;verbosity=normal'
```

Formatted changed C# files with the repository settings:

```bash
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs --verbosity quiet
```

Passed. `git diff --check` also passed. Native device/IDE validation was
not run. Existing device/UI CI failures remain untriaged. No check runs
or commit-status entries were available for the newly pushed head when
checked. The earlier hosted test gate skipped metadata-update cases, so
its result is not evidence that these runtime cases executed.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Partially addresses #36732: resource additions, including implicit
styles.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 22, 2026
<!-- 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!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Fix source-generated incremental XAML Hot Reload resource additions.
Adding an implicit `Label` style in `App.xaml` or a merged `Styles.xaml`
now updates existing labels through the normal resource-change
notifications.

The update writer skipped implicit styles because they have no explicit
`x:Key`, treated explicit `ResourceDictionary` containers as resource
values, and routed dictionary-root child additions through the generic
content-property path.

The new addition paths reuse the normal inflation visitors and existing
resource dictionary APIs: `Add` for eager resources and `AddFactory` for
lazy resources, including implicit styles. Existing keys are guarded so
these additions do not replace existing resources. Existing merged
dictionaries, application-added resources, and live controls remain in
place. Guards apply before constructing eager implicit styles as well as
before registering lazy factories.

Added resources retain the normal lazy and `x:Shared` behavior,
inherited `x:DataType`, and outer `x:Reference` bindings. Retained named
elements are resolved through the live namescope (including explicit
Content/Resources subtrees), and added eager named resources register
their live names, compatible fields, and component IDs. Ancestor
data-type context is cloned and normalized, including
`x:DataType="{x:Type local:Person}"`, without mutating the cached tree.
Top-level keyed `OnPlatform<T>` additions are simplified through their
synthetic dictionary parent so the selected platform value is inflated.

Resource-local and inherited `mc:Ignorable` declarations and
ignore-prefix lists are preserved and normalized on cloned context.
Pruning receives the synthetic dictionary parent, preventing generator
crashes and runtime design-time property assignments. Added eager
resources are created and registered before reference-dependent
properties are initialized, allowing forward `x:Reference` between
resources added in the same update. Live-name and compatible-field
assignment also covers non-Element resources; dictionary-root field
assignment is independent of the Element-only namescope and StyleId
handling.

Addition-only implicit resource containers use guarded inflation rather
than reconstructing unchanged resources; retained keyless class styles
do not disqualify this path. Successfully inserted keyed resources merge
into the existing resource-key bookkeeping so subsequent implicit
removals keep working, without claiming keys that already existed at
runtime. Other implicit update/removal edits keep the existing path. Hot
Reload factories and deferred initializers, including nested resource
factories, use local functions with explicit delegates to avoid
introducing compiler-cached lambda fields during metadata updates. Names
in separate template/style scopes are excluded from the outer reference
map and live field assignment.

This revision removes the earlier Core, runtime registry, public API,
ownership-snapshot, and binding-subscription changes. Production changes
are confined to the source generator's update writer,
patch-input/context plumbing, and directly related
comparison/resource-factory helpers. It does not add general resource
replacement/removal reconciliation or change ordinary runtime resource
behavior.

Targets **`main`**. Broader resource-update and
collection-reconciliation cases are outside this PR's scope.

**Validation**

Latest review follow-up, commit `17b1d8c04e`, using the worktree's .NET
11 RC2 SDK and repository-absolute project paths:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --verbosity quiet
```

Passed: **708**, failed: **0**, skipped: **0**.

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~Maui37888Tests --verbosity quiet
```

Passed: **43**, failed: **0**, skipped: **0**.

The expanded regressions reproduced the new failures before the fixes:
resource-local and inherited ignore-prefix handling, forward references
between eager additions, non-Element named-resource assignment, retained
class-style preservation, and add-B/replace-with-C implicit resource
bookkeeping. Collision regressions prepopulate the exact incoming
keyed-resource or implicit-style key with a runtime factory, assert no
factory realization or incoming construction during the update, and
verify preservation through the following removal edit. Both implicit
and explicit containers are covered, including eager and lazy implicit
styles. Named dictionary-root cases exercise the SourceGen-only
configuration: diagnostics/runtime fallback is disabled because the
pre-existing fallback emits Element-only name lookups for dictionary
roots.

Earlier follow-up regressions independently reproduced all five prior
review findings before their fixes: null references to retained explicit
subtrees, `OnPlatform<Color>` wrappers instead of selected colors,
missing live names for added named resources, CS0103 for inherited
`x:Type` data-type context, and unexpected existing-resource
construction in implicit containers. Tests cover lazy/eager references,
compatible named fields and chained additions, Android/iOS/MacCatalyst
target-framework selection (including a dictionary root), configured
resource identity/construction counts, and template/style scope
isolation. Exercising nested resources followed by another addition also
exposed a metadata-update crash; propagating the local-function factory
form to nested additions fixes it.

The full suite includes real metadata-update cases for implicit and
explicit App.xaml resource containers and a classless merged Styles.xaml
dictionary. These verify existing/new consumers, keyed additions, and
preservation of existing resources and controls. In the earlier worktree
(`repo=/Users/sde/Projects/Microsoft/maui-pr-39826`), the following
focused command reproduced all **3 failures** before the generator fix,
with an unchanged null background instead of red; all three pass in the
latest full-suite run:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$repo/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~AddingApplicationResources_UpdatesExistingAndNewConsumers --logger 'console;verbosity=normal'
```

Formatted changed C# files with the repository settings:

```bash
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs --verbosity quiet
```

Passed. `git diff --check` also passed. Native device/IDE validation was
not run. Existing device/UI CI failures remain untriaged. No check runs
or commit-status entries were available for the newly pushed head when
checked. The earlier hosted test gate skipped metadata-update cases, so
its result is not evidence that these runtime cases executed.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Partially addresses #36732: resource additions, including implicit
styles.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 23, 2026
<!-- 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!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Fix source-generated incremental XAML Hot Reload resource additions.
Adding an implicit `Label` style in `App.xaml` or a merged `Styles.xaml`
now updates existing labels through the normal resource-change
notifications.

The update writer skipped implicit styles because they have no explicit
`x:Key`, treated explicit `ResourceDictionary` containers as resource
values, and routed dictionary-root child additions through the generic
content-property path.

The new addition paths reuse the normal inflation visitors and existing
resource dictionary APIs: `Add` for eager resources and `AddFactory` for
lazy resources, including implicit styles. Existing keys are guarded so
these additions do not replace existing resources. Existing merged
dictionaries, application-added resources, and live controls remain in
place. Guards apply before constructing eager implicit styles as well as
before registering lazy factories.

Added resources retain the normal lazy and `x:Shared` behavior,
inherited `x:DataType`, and outer `x:Reference` bindings. Retained named
elements are resolved through the live namescope (including explicit
Content/Resources subtrees), and added eager named resources register
their live names, compatible fields, and component IDs. Ancestor
data-type context is cloned and normalized, including
`x:DataType="{x:Type local:Person}"`, without mutating the cached tree.
Top-level keyed `OnPlatform<T>` additions are simplified through their
synthetic dictionary parent so the selected platform value is inflated.

Resource-local and inherited `mc:Ignorable` declarations and
ignore-prefix lists are preserved and normalized on cloned context.
Pruning receives the synthetic dictionary parent, preventing generator
crashes and runtime design-time property assignments. Added eager
resources are created and registered before reference-dependent
properties are initialized, allowing forward `x:Reference` between
resources added in the same update. Live-name and compatible-field
assignment also covers non-Element resources; dictionary-root field
assignment is independent of the Element-only namescope and StyleId
handling.

Addition-only implicit resource containers use guarded inflation rather
than reconstructing unchanged resources; retained keyless class styles
do not disqualify this path. Successfully inserted keyed resources merge
into the existing resource-key bookkeeping so subsequent implicit
removals keep working, without claiming keys that already existed at
runtime. Other implicit update/removal edits keep the existing path. Hot
Reload factories and deferred initializers, including nested resource
factories, use local functions with explicit delegates to avoid
introducing compiler-cached lambda fields during metadata updates. Names
in separate template/style scopes are excluded from the outer reference
map and live field assignment.

This revision removes the earlier Core, runtime registry, public API,
ownership-snapshot, and binding-subscription changes. Production changes
are confined to the source generator's update writer,
patch-input/context plumbing, and directly related
comparison/resource-factory helpers. It does not add general resource
replacement/removal reconciliation or change ordinary runtime resource
behavior.

Targets **`main`**. Broader resource-update and
collection-reconciliation cases are outside this PR's scope.

**Validation**

Latest review follow-up, commit `17b1d8c04e`, using the worktree's .NET
11 RC2 SDK and repository-absolute project paths:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --verbosity quiet
```

Passed: **708**, failed: **0**, skipped: **0**.

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~Maui37888Tests --verbosity quiet
```

Passed: **43**, failed: **0**, skipped: **0**.

The expanded regressions reproduced the new failures before the fixes:
resource-local and inherited ignore-prefix handling, forward references
between eager additions, non-Element named-resource assignment, retained
class-style preservation, and add-B/replace-with-C implicit resource
bookkeeping. Collision regressions prepopulate the exact incoming
keyed-resource or implicit-style key with a runtime factory, assert no
factory realization or incoming construction during the update, and
verify preservation through the following removal edit. Both implicit
and explicit containers are covered, including eager and lazy implicit
styles. Named dictionary-root cases exercise the SourceGen-only
configuration: diagnostics/runtime fallback is disabled because the
pre-existing fallback emits Element-only name lookups for dictionary
roots.

Earlier follow-up regressions independently reproduced all five prior
review findings before their fixes: null references to retained explicit
subtrees, `OnPlatform<Color>` wrappers instead of selected colors,
missing live names for added named resources, CS0103 for inherited
`x:Type` data-type context, and unexpected existing-resource
construction in implicit containers. Tests cover lazy/eager references,
compatible named fields and chained additions, Android/iOS/MacCatalyst
target-framework selection (including a dictionary root), configured
resource identity/construction counts, and template/style scope
isolation. Exercising nested resources followed by another addition also
exposed a metadata-update crash; propagating the local-function factory
form to nested additions fixes it.

The full suite includes real metadata-update cases for implicit and
explicit App.xaml resource containers and a classless merged Styles.xaml
dictionary. These verify existing/new consumers, keyed additions, and
preservation of existing resources and controls. In the earlier worktree
(`repo=/Users/sde/Projects/Microsoft/maui-pr-39826`), the following
focused command reproduced all **3 failures** before the generator fix,
with an unchanged null background instead of red; all three pass in the
latest full-suite run:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$repo/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~AddingApplicationResources_UpdatesExistingAndNewConsumers --logger 'console;verbosity=normal'
```

Formatted changed C# files with the repository settings:

```bash
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs --verbosity quiet
```

Passed. `git diff --check` also passed. Native device/IDE validation was
not run. Existing device/UI CI failures remain untriaged. No check runs
or commit-status entries were available for the newly pushed head when
checked. The earlier hosted test gate skipped metadata-update cases, so
its result is not evidence that these runtime cases executed.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Partially addresses #36732: resource additions, including implicit
styles.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
@kubaflo kubaflo added this to the .NET 11 SR2 milestone Nov 24, 2026
KarthikRajaKalaimani pushed a commit to KarthikRajaKalaimani/maui that referenced this pull request Nov 26, 2026
<!-- 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!

<!--
!!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING
MAIN. !!!!!!!
-->

### Description of Change

<!-- Enter description of the fix in this section -->

Fix source-generated incremental XAML Hot Reload resource additions.
Adding an implicit `Label` style in `App.xaml` or a merged `Styles.xaml`
now updates existing labels through the normal resource-change
notifications.

The update writer skipped implicit styles because they have no explicit
`x:Key`, treated explicit `ResourceDictionary` containers as resource
values, and routed dictionary-root child additions through the generic
content-property path.

The new addition paths reuse the normal inflation visitors and existing
resource dictionary APIs: `Add` for eager resources and `AddFactory` for
lazy resources, including implicit styles. Existing keys are guarded so
these additions do not replace existing resources. Existing merged
dictionaries, application-added resources, and live controls remain in
place. Guards apply before constructing eager implicit styles as well as
before registering lazy factories.

Added resources retain the normal lazy and `x:Shared` behavior,
inherited `x:DataType`, and outer `x:Reference` bindings. Retained named
elements are resolved through the live namescope (including explicit
Content/Resources subtrees), and added eager named resources register
their live names, compatible fields, and component IDs. Ancestor
data-type context is cloned and normalized, including
`x:DataType="{x:Type local:Person}"`, without mutating the cached tree.
Top-level keyed `OnPlatform<T>` additions are simplified through their
synthetic dictionary parent so the selected platform value is inflated.

Resource-local and inherited `mc:Ignorable` declarations and
ignore-prefix lists are preserved and normalized on cloned context.
Pruning receives the synthetic dictionary parent, preventing generator
crashes and runtime design-time property assignments. Added eager
resources are created and registered before reference-dependent
properties are initialized, allowing forward `x:Reference` between
resources added in the same update. Live-name and compatible-field
assignment also covers non-Element resources; dictionary-root field
assignment is independent of the Element-only namescope and StyleId
handling.

Addition-only implicit resource containers use guarded inflation rather
than reconstructing unchanged resources; retained keyless class styles
do not disqualify this path. Successfully inserted keyed resources merge
into the existing resource-key bookkeeping so subsequent implicit
removals keep working, without claiming keys that already existed at
runtime. Other implicit update/removal edits keep the existing path. Hot
Reload factories and deferred initializers, including nested resource
factories, use local functions with explicit delegates to avoid
introducing compiler-cached lambda fields during metadata updates. Names
in separate template/style scopes are excluded from the outer reference
map and live field assignment.

This revision removes the earlier Core, runtime registry, public API,
ownership-snapshot, and binding-subscription changes. Production changes
are confined to the source generator's update writer,
patch-input/context plumbing, and directly related
comparison/resource-factory helpers. It does not add general resource
replacement/removal reconciliation or change ordinary runtime resource
behavior.

Targets **`main`**. Broader resource-update and
collection-reconciliation cases are outside this PR's scope.

**Validation**

Latest review follow-up, commit `17b1d8c04e`, using the worktree's .NET
11 RC2 SDK and repository-absolute project paths:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --verbosity quiet
```

Passed: **708**, failed: **0**, skipped: **0**.

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$PWD/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~Maui37888Tests --verbosity quiet
```

Passed: **43**, failed: **0**, skipped: **0**.

The expanded regressions reproduced the new failures before the fixes:
resource-local and inherited ignore-prefix handling, forward references
between eager additions, non-Element named-resource assignment, retained
class-style preservation, and add-B/replace-with-C implicit resource
bookkeeping. Collision regressions prepopulate the exact incoming
keyed-resource or implicit-style key with a runtime factory, assert no
factory realization or incoming construction during the update, and
verify preservation through the following removal edit. Both implicit
and explicit containers are covered, including eager and lazy implicit
styles. Named dictionary-root cases exercise the SourceGen-only
configuration: diagnostics/runtime fallback is disabled because the
pre-existing fallback emits Element-only name lookups for dictionary
roots.

Earlier follow-up regressions independently reproduced all five prior
review findings before their fixes: null references to retained explicit
subtrees, `OnPlatform<Color>` wrappers instead of selected colors,
missing live names for added named resources, CS0103 for inherited
`x:Type` data-type context, and unexpected existing-resource
construction in implicit containers. Tests cover lazy/eager references,
compatible named fields and chained additions, Android/iOS/MacCatalyst
target-framework selection (including a dictionary root), configured
resource identity/construction counts, and template/style scope
isolation. Exercising nested resources followed by another addition also
exposed a metadata-update crash; propagating the local-function factory
form to nested additions fixes it.

The full suite includes real metadata-update cases for implicit and
explicit App.xaml resource containers and a classless merged Styles.xaml
dictionary. These verify existing/new consumers, keyed additions, and
preservation of existing resources and controls. In the earlier worktree
(`repo=/Users/sde/Projects/Microsoft/maui-pr-39826`), the following
focused command reproduced all **3 failures** before the generator fix,
with an unchanged null background instead of red; all three pass in the
latest full-suite run:

```bash
DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test "$repo/src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj" -c Debug --no-restore --filter FullyQualifiedName~AddingApplicationResources_UpdatesExistingAndNewConsumers --logger 'console;verbosity=normal'
```

Formatted changed C# files with the repository settings:

```bash
dotnet format Microsoft.Maui.sln --no-restore --exclude Templates/src --exclude-diagnostics CA1822 --include src/Controls/src/SourceGen/UpdateComponentCodeWriter.cs src/Controls/tests/SourceGen.UnitTests/HotReload/Maui37888Tests.cs src/Controls/tests/SourceGen.UnitTests/HotReload/XamlHotReloadTestHarness.cs src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs --verbosity quiet
```

Passed. `git diff --check` also passed. Native device/IDE validation was
not run. Existing device/UI CI failures remain untriaged. No check runs
or commit-status entries were available for the newly pushed head when
checked. The earlier hosted test gate skipped metadata-update cases, so
its result is not evidence that these runtime cases executed.

### Issues Fixed

<!-- Please make sure that there is a bug logged for the issue being
fixed. The bug should describe the problem and how to reproduce it. -->

Partially addresses dotnet#36732: resource additions, including implicit
styles.

<!--
Are you targeting main? All PRs should target the main branch unless
otherwise noted.
-->

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants