Skip to content

[XAML] Refresh implicit styles after incremental Hot Reload setter edits - #39928

Merged
kubaflo merged 2 commits into
mainfrom
stephanedelcroix-issue-39780-reproduction
Nov 6, 2026
Merged

kubaflo merged 2 commits into
mainfrom
stephanedelcroix-issue-39780-reproduction

Conversation

@StephaneDelcroix

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 scalar Setter.Value edits in implicit styles declared in root resource dictionaries, including classless dictionaries merged through Source=.

The existing patch tries to mutate a Setter that may only exist inside a lazy resource factory. Even when that node is available, assigning through the object-typed Setter.Value bypasses the target property's conversion, and mutating a Setter does not reapply the Style to existing consumers.

Regenerate the owning implicit Style through the initialization visitor pipeline and replace its resource entry once per patch. This converts the setter values correctly and notifies existing implicit-style consumers without replacing their controls or overriding local values. Preserve lazy resource factories and x:Shared semantics; replacement factories use node-ID-based local-function names to retain Edit-and-Continue identity across successive edits. Other style-edit shapes retain their existing handling.

Add generator and live metadata-update regression tests covering classless Source= dictionaries, successive edits/reverts, multiple changed setters, BasedOn, x:Type, existing/new consumers, local-value precedence, and shared/non-shared resource identity.

Issues Fixed

Fixes #39780

Validation

  • DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj -v quiet — passed: 675 tests, no failures or skips.
  • DOTNET_MODIFIABLE_ASSEMBLIES=debug pwsh .github/skills/verify-tests-fail-without-fix/scripts/verify-tests-fail.ps1 -PRNumber local-39780 -BaseBranch af342571745d33712c43fc1050f606a535a3dafd -RequireFullVerification — VERIFICATION PASSED: all six regression cases failed without the fix and passed with it. local-39780 is the local verification output identifier, not a PR number.

Managed generator/runtime validation was performed on macOS against current main. Native Windows rendering, Visual Studio, and dotnet watch were not exercised.

StephaneDelcroix and others added 2 commits November 5, 2026 14:45
Regenerate the owning implicit Style through the initialization pipeline and replace its ResourceDictionary entry so retained consumers are refreshed.

Fixes #39780

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Keep x:Shared semantics when replacing an implicit Style and use a node-ID-named local factory to preserve Edit-and-Continue identity across successive updates.

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

github-actions Bot commented Nov 5, 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 -- 39928

Or

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

@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

Setter edits can break external x:Reference resolution and leave eager-style registry entries and named fields pointing to stale objects, causing subsequent edits to update a detached style.

2 open issues
What changed in this PR

Addresses #39780 by regenerating implicit styles after scalar setter edits during incremental XAML Hot Reload, allowing existing controls to receive converted values through resource replacement.

Changes:

  • Rebuilds each affected implicit style once per patch using the initialization visitors.
  • Adds stable replacement factory names while retaining lazy creation and x:Shared behavior.
  • Adds generator and live-update regression coverage for merged dictionaries, successive edits, resource identity, and local-value precedence.
File Description
src/​Controls/​tests/​SourceGen.UnitTests/​HotReload/​Maui39780Tests.cs Adds generator and runtime regression tests for implicit-style updates.
src/​Controls/​src/​SourceGen/​UpdateComponentCodeWriter.cs Detects scalar setter edits and emits implicit-style replacements.
src/​Controls/​src/​SourceGen/​SetPropertyHelpers.cs Supports replacing lazy resources using stable local factory functions.

Review effort: Balanced

{
var context = CreateConversionContext(compilation, sourceProductionContext, xmlnsCache,
typeCache, rootType, projectItem, codeWriter);
context.Variables[dictionary] = new DirectValue(rootType, "this");
replacement.Accept(new SetResourcesVisitor(context), null);
replacement.Accept(new SetPropertiesVisitor(context, stopOnResourceDictionary: true), null);
var styleVariable = context.Variables[replacement].ValueAccessor;
codeWriter.WriteLine($"this[{styleVariable}.TargetType.FullName!] = {styleVariable};");
@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 5, 2026
@azure-pipelines

This comment has been minimized.

@MauiBot

MauiBot commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

PR Test Gate

@StephaneDelcroix — existing-test verification for commit 12d10d24.

Result PASSED Platform Android Commit 12d10d24


🧪 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
Maui39780Tests ✅ Failed as expected (71s) ✅ Passed (27s)
Execution log excerpts

Without fix Maui39780Tests

     at Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.Maui39780Tests.ImplicitStyleSetterPatch_ReplacesStyleResource() in /_/src/Controls/tests/SourceGen.UnitTests/HotReload/Maui39780Tests.cs:line 45
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)

With fix Maui39780Tests

780Tests.ImplicitStyleSetterPatch_ReplacesStyleResource [5 s]
[xUnit.net 00:00:06.27]     Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.Maui39780Tests.ClasslessSourceDictionary_ImplicitStyleSetter_UpdatesExistingLabel [SKIP]
[xUnit.net 00:00:06.28]       Requires runtime support for applying metadata updates. Set DOTNET_MODIFIABLE_ASSEMBLIES=debug in the environment to run these tests.
[xUnit.net 00:00:06.28]     Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.Maui39780Tests.ImplicitStyleSetter_InMergedDictionary_UpdatesExistingLabel [SKIP]
[xUnit.net 00:00:06.28]       Requires runtime support for applying metadata updates. Set DOTNET_MODIFIABLE_ASSEMBLIES=debug in the environment to run these tests.
[xUnit.net 00:00:06.28]   Finished:    Microsoft.Maui.Controls.SourceGen.UnitTests
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.Maui39780Tests.ClasslessSourceDictionary_ImplicitStyleSetter_UpdatesExistingLabel [1 ms]
  Skipped Microsoft.Maui.Controls.SourceGen.UnitTests.HotReload.Maui39780Tests.ImplicitStyleSetter_InMergedDictionary_UpdatesExistingLabel [1 ms]
Test Run Successful.
Total tests: 3
     Passed: 1
    Skipped: 2
 Total time: 7.2842 Seconds

PR head: 12d10d24.

Without-fix baseline: f3b45e18.

@MauiBot MauiBot added s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) and removed s/agent-review-in-progress AI review is currently running for this PR labels Nov 5, 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 — 4 findings

Reviewed commit 12d10d2.

See inline comments for details.

{
var context = CreateConversionContext(compilation, sourceProductionContext, xmlnsCache,
typeCache, rootType, projectItem, codeWriter);
context.Variables[dictionary] = new DirectValue(rootType, "this");

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 - Preserve enclosing name mappings when regenerating the style. An implicit Label style can have an unchanged BindingContext setter using {x:Reference Root} to the dictionary's x:Name beside the edited TextColor setter. This fresh context contains only the dictionary variable; its scopes and parent context do not contain Root. KnownMarkups.ProvideValueForReferenceExtension consequently reports name-not-found while rebuilding the unchanged setter, so changing only Red to Blue now produces a generator error for previously valid XAML. Carry the enclosing name-to-live-object mappings into the replacement context and cover this mixed-setter case.

replacement.Accept(new SetResourcesVisitor(context), null);
replacement.Accept(new SetPropertiesVisitor(context, stopOnResourceDictionary: true), null);
var styleVariable = context.Variables[replacement].ValueAccessor;
codeWriter.WriteLine($"this[{styleVariable}.TargetType.FullName!] = {styleVariable};");

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 - Reconcile replacement node IDs and named fields, not just the resource entry. With MauiXamlLazyRD=false, or an implicit Style carrying x:Name, initialization registers the original style/setters and assigns generated fields. This branch replaces the dictionary entry without emitting replacement registrations or field assignments. After a scalar setter edit, a subsequent ApplyToDerivedTypes edit therefore resolves the detached original through XamlComponentRegistry.TryGet, leaving the replacement unchanged and new derived controls unstyled. Named fields also immediately expose the old objects. Add an eager/named-style regression checking field/resource identity and a subsequent non-setter edit.

var replacedStyles = new HashSet<ElementNode>();
foreach (var nodeDiff in diff.NodeChanges)
{
bool isRoot = string.IsNullOrEmpty(nodeDiff.NodeId);

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 - Update sibling resources before publishing replacement styles. With lazy resources enabled, declare an implicit Label style before a Color resource keyed Accent, give the style an unchanged BackgroundColor="{StaticResource Accent}" setter, and change both a scalar TextColor setter and Accent in one save. XamlNodeDiff emits node changes in tree order. The replacement AddFactory notification synchronously resolves the style for existing consumers and caches its old Accent value before TryEmitResourceDictionaryItemChange updates Accent. That later notification cannot refresh a StaticResource setter, so existing and newly added labels use the stale background. Defer replacement publication until the resource updates have been applied and cover a combined edit.

replacement.Accept(new XamlNodeVisitor((node, parentNode) => node.Parent = parentNode), dictionary);
replacement.Accept(new ExpandMarkupsVisitor(context), null);
replacement.Accept(new PruneIgnoredNodesVisitor(), null);
replacement.Accept(new SimplifyTypeExtensionVisitor(), 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.

[moderate] XAML & Bindings - Normalize inherited type metadata as well as the cloned style. For a dictionary declaring x:DataType="{x:Type vm:ViewModel}", an implicit style can contain an unchanged {Binding Caption} setter beside the edited scalar setter. Only the clone is expanded/simplified here; its dictionary parent remains the raw parsed diff tree. When the binding is regenerated, KnownMarkups.TryGetXDataType reaches the parent's unexpanded MarkupNode and reports that the data type is not a value node. Normal InitializeComponent normalizes the entire root, so this valid initial XAML fails specifically after the scalar edit. Supply resolved ancestor metadata and add a root x:DataType markup regression.

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

Style replacement loses enclosing reference and type metadata, causing valid XAML patches to fail compilation, and leaves registry entries and named fields pointing to detached styles.

4 open issues

Review effort: Balanced

Comment on lines +1328 to +1330
replacement.Accept(new ExpandMarkupsVisitor(context), null);
replacement.Accept(new PruneIgnoredNodesVisitor(), null);
replacement.Accept(new SimplifyTypeExtensionVisitor(), null);
Comment on lines +122 to +124
if (TryEmitImplicitStyleSetterChange(codeWriter, nodeDiff, replacedStyles, newIds,
compilation, xmlnsCache, typeCache, rootType, sourceProductionContext, projectItem))
continue;
@kubaflo
kubaflo merged commit ae2a26c into main Nov 6, 2026
151 of 186 checks passed
@kubaflo
kubaflo deleted the stephanedelcroix-issue-39780-reproduction branch November 6, 2026 07:56
kubaflo added a commit that referenced this pull request Nov 20, 2026
…dits (#40418)

<!-- 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!

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

Targets `main`: this is XAML incremental hot reload work, like #39928,
and it adds a generator-only public API.

### Description of Change

When a `Setter.Value` changed on a keyed `Style` or a `Class` style in a
root `ResourceDictionary`, `UpdateComponent()` emitted something like
`((Setter)node!).Value = "Blue";`. That assigns an unconverted string
and never reapplies the style, so existing consumers kept stale values.
With lazy resources, even new consumers kept them. #39928 fixed implicit
styles by replacing the dictionary entry. That doesn't help keyed or
Class styles, because `StaticResource`, `StyleClass` and `BasedOn`
consumers hold the `Style` instance directly.

Changes:
- **Generator** (`UpdateComponentCodeWriter`, `SetPropertyHelpers`):
setter-value edits on keyed and Class styles in a root RD now rebuild
the style through the normal IC visitor pipeline, as for implicit
styles, and call `XamlComponentRegistry.TryUpdateStyle`. Fallback when
that returns false:
  - Lazy keyed styles: replace the factory.
  - Eager keyed styles: assign the dictionary entry.
- Class styles: no fallback, since they live in a shared per-class list.
  
  The implicit-style path is unchanged.
- **`XamlComponentRegistry.TryUpdateStyle`** (new public,
`EditorBrowsable(Never)`): finds the live style without forcing lazy
factories. That means a shared, already-materialized lazy entry, an
eager entry, or the single matching entry in a class list. If only the
setters changed, it replaces them in place; otherwise it returns false.
"Only the setters" means the same TargetType, Class, BasedOn,
BaseResourceKey, ApplyToDerivedTypes and CanCascade.
- **`Style.ReplaceSetters`** (internal): unapplies the old setters from
all tracked targets, swaps them, and reapplies the new ones with each
target's specificity. Derived-style consumers are covered because a base
style tracks them with `AsBaseStyle` specificity. Local values still
win.
- **`ResourceDictionary.TryGetLocalMaterializedValue`** /
**`LazyResource.TryGetCachedValue`** (internal): let the helper peek at
an entry without resolving it.

Known limitations:
- Existing consumers of `x:Shared="False"` styles can't be refreshed,
because the instances aren't tracked. New consumers get the new value.
- Styles declared in a page's own `Resources` are out of scope; this
matches #39928, which also covers only root resource dictionaries.

### Issues Fixed

Fixes #39984

### Validation

New tests are in
`src/Controls/tests/SourceGen.UnitTests/HotReload/Maui39984Tests.cs`,
run with both lazy and eager RD. I added a `LazyRD` option to the test
harness for them. They cover:
- the generated patch shape
- live StaticResource, DynamicResource and locally overridden consumers
- `BasedOn` propagation
- StyleClass consumers
- unresolved lazy styles and `x:Shared="False"` styles

The new tests failed (8 of 8) before the fix. Commands run:

- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
Microsoft.Maui.Controls.SourceGen.UnitTests.dll --filter
"FullyQualifiedName~Maui39984|FullyQualifiedName~Maui39780"`:
**Passed**, 14/14. I ran it from a copy of the build output outside the
`~`-containing worktree path.
- Same command, full SourceGen.UnitTests suite: **Passed**, 683/683.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj`: 6733
passed, 1 failed. The failure is
`TwoWayBindingToNullableDoublePropertyWithEmptyStringBecomesNull`, which
also fails without this change: it's locale-dependent ("3,14" vs
"3.14").
- `dotnet build src/Controls/src/Xaml/Controls.Xaml.csproj -f
netstandard2.0`: succeeded with no PublicAPI errors.

I did not test this on a device or in Visual Studio.

---------

Co-authored-by: Copilot App <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
…dits (#40418)

<!-- 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!

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

Targets `main`: this is XAML incremental hot reload work, like #39928,
and it adds a generator-only public API.

### Description of Change

When a `Setter.Value` changed on a keyed `Style` or a `Class` style in a
root `ResourceDictionary`, `UpdateComponent()` emitted something like
`((Setter)node!).Value = "Blue";`. That assigns an unconverted string
and never reapplies the style, so existing consumers kept stale values.
With lazy resources, even new consumers kept them. #39928 fixed implicit
styles by replacing the dictionary entry. That doesn't help keyed or
Class styles, because `StaticResource`, `StyleClass` and `BasedOn`
consumers hold the `Style` instance directly.

Changes:
- **Generator** (`UpdateComponentCodeWriter`, `SetPropertyHelpers`):
setter-value edits on keyed and Class styles in a root RD now rebuild
the style through the normal IC visitor pipeline, as for implicit
styles, and call `XamlComponentRegistry.TryUpdateStyle`. Fallback when
that returns false:
  - Lazy keyed styles: replace the factory.
  - Eager keyed styles: assign the dictionary entry.
- Class styles: no fallback, since they live in a shared per-class list.
  
  The implicit-style path is unchanged.
- **`XamlComponentRegistry.TryUpdateStyle`** (new public,
`EditorBrowsable(Never)`): finds the live style without forcing lazy
factories. That means a shared, already-materialized lazy entry, an
eager entry, or the single matching entry in a class list. If only the
setters changed, it replaces them in place; otherwise it returns false.
"Only the setters" means the same TargetType, Class, BasedOn,
BaseResourceKey, ApplyToDerivedTypes and CanCascade.
- **`Style.ReplaceSetters`** (internal): unapplies the old setters from
all tracked targets, swaps them, and reapplies the new ones with each
target's specificity. Derived-style consumers are covered because a base
style tracks them with `AsBaseStyle` specificity. Local values still
win.
- **`ResourceDictionary.TryGetLocalMaterializedValue`** /
**`LazyResource.TryGetCachedValue`** (internal): let the helper peek at
an entry without resolving it.

Known limitations:
- Existing consumers of `x:Shared="False"` styles can't be refreshed,
because the instances aren't tracked. New consumers get the new value.
- Styles declared in a page's own `Resources` are out of scope; this
matches #39928, which also covers only root resource dictionaries.

### Issues Fixed

Fixes #39984

### Validation

New tests are in
`src/Controls/tests/SourceGen.UnitTests/HotReload/Maui39984Tests.cs`,
run with both lazy and eager RD. I added a `LazyRD` option to the test
harness for them. They cover:
- the generated patch shape
- live StaticResource, DynamicResource and locally overridden consumers
- `BasedOn` propagation
- StyleClass consumers
- unresolved lazy styles and `x:Shared="False"` styles

The new tests failed (8 of 8) before the fix. Commands run:

- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
Microsoft.Maui.Controls.SourceGen.UnitTests.dll --filter
"FullyQualifiedName~Maui39984|FullyQualifiedName~Maui39780"`:
**Passed**, 14/14. I ran it from a copy of the build output outside the
`~`-containing worktree path.
- Same command, full SourceGen.UnitTests suite: **Passed**, 683/683.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj`: 6733
passed, 1 failed. The failure is
`TwoWayBindingToNullableDoublePropertyWithEmptyStringBecomesNull`, which
also fails without this change: it's locale-dependent ("3,14" vs
"3.14").
- `dotnet build src/Controls/src/Xaml/Controls.Xaml.csproj -f
netstandard2.0`: succeeded with no PublicAPI errors.

I did not test this on a device or in Visual Studio.

---------

Co-authored-by: Copilot App <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
…dits (#40418)

<!-- 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!

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

Targets `main`: this is XAML incremental hot reload work, like #39928,
and it adds a generator-only public API.

### Description of Change

When a `Setter.Value` changed on a keyed `Style` or a `Class` style in a
root `ResourceDictionary`, `UpdateComponent()` emitted something like
`((Setter)node!).Value = "Blue";`. That assigns an unconverted string
and never reapplies the style, so existing consumers kept stale values.
With lazy resources, even new consumers kept them. #39928 fixed implicit
styles by replacing the dictionary entry. That doesn't help keyed or
Class styles, because `StaticResource`, `StyleClass` and `BasedOn`
consumers hold the `Style` instance directly.

Changes:
- **Generator** (`UpdateComponentCodeWriter`, `SetPropertyHelpers`):
setter-value edits on keyed and Class styles in a root RD now rebuild
the style through the normal IC visitor pipeline, as for implicit
styles, and call `XamlComponentRegistry.TryUpdateStyle`. Fallback when
that returns false:
  - Lazy keyed styles: replace the factory.
  - Eager keyed styles: assign the dictionary entry.
- Class styles: no fallback, since they live in a shared per-class list.
  
  The implicit-style path is unchanged.
- **`XamlComponentRegistry.TryUpdateStyle`** (new public,
`EditorBrowsable(Never)`): finds the live style without forcing lazy
factories. That means a shared, already-materialized lazy entry, an
eager entry, or the single matching entry in a class list. If only the
setters changed, it replaces them in place; otherwise it returns false.
"Only the setters" means the same TargetType, Class, BasedOn,
BaseResourceKey, ApplyToDerivedTypes and CanCascade.
- **`Style.ReplaceSetters`** (internal): unapplies the old setters from
all tracked targets, swaps them, and reapplies the new ones with each
target's specificity. Derived-style consumers are covered because a base
style tracks them with `AsBaseStyle` specificity. Local values still
win.
- **`ResourceDictionary.TryGetLocalMaterializedValue`** /
**`LazyResource.TryGetCachedValue`** (internal): let the helper peek at
an entry without resolving it.

Known limitations:
- Existing consumers of `x:Shared="False"` styles can't be refreshed,
because the instances aren't tracked. New consumers get the new value.
- Styles declared in a page's own `Resources` are out of scope; this
matches #39928, which also covers only root resource dictionaries.

### Issues Fixed

Fixes #39984

### Validation

New tests are in
`src/Controls/tests/SourceGen.UnitTests/HotReload/Maui39984Tests.cs`,
run with both lazy and eager RD. I added a `LazyRD` option to the test
harness for them. They cover:
- the generated patch shape
- live StaticResource, DynamicResource and locally overridden consumers
- `BasedOn` propagation
- StyleClass consumers
- unresolved lazy styles and `x:Shared="False"` styles

The new tests failed (8 of 8) before the fix. Commands run:

- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
Microsoft.Maui.Controls.SourceGen.UnitTests.dll --filter
"FullyQualifiedName~Maui39984|FullyQualifiedName~Maui39780"`:
**Passed**, 14/14. I ran it from a copy of the build output outside the
`~`-containing worktree path.
- Same command, full SourceGen.UnitTests suite: **Passed**, 683/683.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj`: 6733
passed, 1 failed. The failure is
`TwoWayBindingToNullableDoublePropertyWithEmptyStringBecomesNull`, which
also fails without this change: it's locale-dependent ("3,14" vs
"3.14").
- `dotnet build src/Controls/src/Xaml/Controls.Xaml.csproj -f
netstandard2.0`: succeeded with no PublicAPI errors.

I did not test this on a device or in Visual Studio.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
KarthikRajaKalaimani pushed a commit to KarthikRajaKalaimani/maui that referenced this pull request Nov 26, 2026
…dits (dotnet#40418)

<!-- 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!

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

Targets `main`: this is XAML incremental hot reload work, like dotnet#39928,
and it adds a generator-only public API.

### Description of Change

When a `Setter.Value` changed on a keyed `Style` or a `Class` style in a
root `ResourceDictionary`, `UpdateComponent()` emitted something like
`((Setter)node!).Value = "Blue";`. That assigns an unconverted string
and never reapplies the style, so existing consumers kept stale values.
With lazy resources, even new consumers kept them. dotnet#39928 fixed implicit
styles by replacing the dictionary entry. That doesn't help keyed or
Class styles, because `StaticResource`, `StyleClass` and `BasedOn`
consumers hold the `Style` instance directly.

Changes:
- **Generator** (`UpdateComponentCodeWriter`, `SetPropertyHelpers`):
setter-value edits on keyed and Class styles in a root RD now rebuild
the style through the normal IC visitor pipeline, as for implicit
styles, and call `XamlComponentRegistry.TryUpdateStyle`. Fallback when
that returns false:
  - Lazy keyed styles: replace the factory.
  - Eager keyed styles: assign the dictionary entry.
- Class styles: no fallback, since they live in a shared per-class list.
  
  The implicit-style path is unchanged.
- **`XamlComponentRegistry.TryUpdateStyle`** (new public,
`EditorBrowsable(Never)`): finds the live style without forcing lazy
factories. That means a shared, already-materialized lazy entry, an
eager entry, or the single matching entry in a class list. If only the
setters changed, it replaces them in place; otherwise it returns false.
"Only the setters" means the same TargetType, Class, BasedOn,
BaseResourceKey, ApplyToDerivedTypes and CanCascade.
- **`Style.ReplaceSetters`** (internal): unapplies the old setters from
all tracked targets, swaps them, and reapplies the new ones with each
target's specificity. Derived-style consumers are covered because a base
style tracks them with `AsBaseStyle` specificity. Local values still
win.
- **`ResourceDictionary.TryGetLocalMaterializedValue`** /
**`LazyResource.TryGetCachedValue`** (internal): let the helper peek at
an entry without resolving it.

Known limitations:
- Existing consumers of `x:Shared="False"` styles can't be refreshed,
because the instances aren't tracked. New consumers get the new value.
- Styles declared in a page's own `Resources` are out of scope; this
matches dotnet#39928, which also covers only root resource dictionaries.

### Issues Fixed

Fixes dotnet#39984

### Validation

New tests are in
`src/Controls/tests/SourceGen.UnitTests/HotReload/Maui39984Tests.cs`,
run with both lazy and eager RD. I added a `LazyRD` option to the test
harness for them. They cover:
- the generated patch shape
- live StaticResource, DynamicResource and locally overridden consumers
- `BasedOn` propagation
- StyleClass consumers
- unresolved lazy styles and `x:Shared="False"` styles

The new tests failed (8 of 8) before the fix. Commands run:

- `DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test
Microsoft.Maui.Controls.SourceGen.UnitTests.dll --filter
"FullyQualifiedName~Maui39984|FullyQualifiedName~Maui39780"`:
**Passed**, 14/14. I ran it from a copy of the build output outside the
`~`-containing worktree path.
- Same command, full SourceGen.UnitTests suite: **Passed**, 683/683.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj`: 6733
passed, 1 failed. The failure is
`TwoWayBindingToNullableDoublePropertyWithEmptyStringBecomesNull`, which
also fails without this change: it's locale-dependent ("3,14" vs
"3.14").
- `dotnet build src/Controls/src/Xaml/Controls.Xaml.csproj -f
netstandard2.0`: succeeded with no PublicAPI errors.

I did not test this on a device or in Visual Studio.

---------

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

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 12d10d24 Deployed Nov 5, 2026 by StephaneDelcroix via conclusion #2721
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.

[XIHR] Changing an implicit Label style Setter in a merged ResourceDictionary silently fails while Hot Reload reports success

4 participants