Skip to content

[XSG] Trimmable Styles - #33561

Merged
kubaflo merged 21 commits into
mainfrom
dev/simonrozsival/trimmable-styles
Nov 26, 2026
Merged

kubaflo merged 21 commits into
mainfrom
dev/simonrozsival/trimmable-styles

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Jan 16, 2026 •

Copy link
Copy Markdown
Member

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!

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

For .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into net11; agents must not retarget or merge.

This is .NET 12 feature work with new public API, so it now targets main. It was rebased from net11.0 onto main at f38825f543.

Description of Change

With NativeAOT and XAML SourceGen, a style no longer keeps its setters, triggers and behaviors (and everything they reference) when the app never creates an instance of the style's TargetType.

This is one of a series of PRs needed for full trimming. It removes style-related roots; it does not make a whole MAUI app fully trimmable on its own.

The feature is on by default only for NativeAOT apps (MauiXamlTrimmableStyles defaults to $(PublishAot)). ILLink does not remove code behind type checks: in a trimmed (non-AOT) publish of the sample below, the unused style's control and payload survived exactly as with an eager style. Other apps would get the behavior changes and no size benefit, so they keep eager styles. Their generated code differs from main only in that implicit styles are registered under a string key; behavior is the same.

Generated code

With trimmable styles enabled, a style whose TargetType is known at compile time is generated as:

__root.Resources.AddFactory("Microsoft.Maui.Controls.Label", () =>
{
    var style = new Style(typeof(global::Microsoft.Maui.Controls.Label));
    bool lazyInitialization(Style __style, BindableObject __target)
    {
        if (__target is global::Microsoft.Maui.Controls.Label target)
        {
            if (__style is null)
                return true;
            // setters, triggers and behaviors are created and added to __style here
            return true;
        }
        return false;
    }
    style.LazyInitialization = new Func<Style, BindableObject, bool>(lazyInitialization);
    return style;
});
  • Positive type-test guard. When T is never instantiated, NativeAOT folds __target is T to false and removes the body. Keep this shape; a negative early return would not be removed. No helper method, NoInlining or GC.KeepAlive is emitted.
  • typeof(T) keeps only the type's identity. In the sample app, an unused target kept just its 316-byte type descriptor, and its setters were still removed. So the style keeps using Style(Type); no new constructor or reflection is needed.
  • String keys for implicit styles. Implicit styles are registered under the target's full name (Type.FullName format, with + for nested types) instead of AddFactory(typeof(T), …), so no Type.FullName lookup runs at startup. Constructed generic targets keep typeof(T) keys, because their runtime names include assembly-qualified type arguments.
  • Local function, not a lambda. A lambda that captures nothing is cached in a compiler-generated static field. XAML Hot Reload cannot add fields to a compiler-generated class created by an earlier update, which caused a TypeLoadException in Maui37888Tests.
  • Fallbacks. Runtime TargetType values such as {x:Static} create the style eagerly, as before. A missing or unresolvable TargetType reports MAUIG1001.
  • Deferred content. A new pre-pass, MarkDeferredStyleContentVisitor, marks the content of each style. XamlNode.Accept then skips only that content, so the style's own properties, diagnostics and Hot Reload registration are still generated in the normal pass. Inline BasedOn styles get their own initializer.

Runtime behavior

  • The only new API is Style.LazyInitialization { internal get; set; } (Func<Style, BindableObject, bool>, EditorBrowsable(Never)), intended for the source generator.
  • The first compatible target populates Setters, Triggers and Behaviors. XAML-declared setters stay ahead of setters added from code. On later applies, the initializer is called with a null style and only checks the target type.
  • A lazy style is only applied to instances of its TargetType. A mismatched element gets nothing, and the mismatch is logged through the element's logger, then the app's logger, then Trace. Mismatched targets are not tracked, so UnApply ignores them.
  • Applies that re-enter during initialization are queued until initialization finishes.
  • If Hot Reload replaces a lazy style's setters before its first apply, the first apply keeps the replaced setters and only adds the initializer's triggers and behaviors.

Behavior differences and opt-out

With trimmable styles enabled:

  • Style.Setters, Triggers and Behaviors are empty until the style is first applied to a compatible element.
  • Before this PR, a style applied to an incompatible element still applied its compatible setters and logged a warning; now nothing is applied. This only happens when Style is set explicitly (StaticResource, DynamicResource, a binding or code); implicit and class styles are already filtered by type.
  • StaticResource values inside setters are resolved on first apply, not at page load.
  • Styles built in C# or by XamlC or the runtime inflator are unchanged.

MAUIX2024 (warning) reports a same-file {StaticResource} style whose TargetType doesn't match the element. MAUIX2020 was already taken on main.

MauiXamlTrimmableStyles defaults to $(PublishAot). It can be set globally or per file:

<MauiXamlTrimmableStyles>false</MauiXamlTrimmableStyles>
<!-- or per file -->
<MauiXaml Update="MyPage.xaml" TrimmableStyles="false" />

See docs/trimmable-styles-spec.md.

Rebase onto main

Review feedback addressed

  • The type name passed to the earlier Style(string) constructor was a C# display name, not a CLR assembly-qualified name. That constructor is gone; styles are identified with typeof(T).
  • Applying a shared style to a wrong-type element first no longer leaves it permanently empty.
  • The missing-TargetType diagnostic tested by Gh2064 is reported again.
  • Maui32879Tests, SetterCompiledConverters and SimplifyOnPlatform failed the earlier gate. They are now unchanged from main and pass.

Validation

Run on 144cbed9ce (macOS arm64, SDK 12.0.100-alpha.1.26523.103, LC_ALL=en_US.UTF-8). Each build passed -p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false.

Command Result
dotnet build src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj, then DOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test artifacts/bin/SourceGen.UnitTests/Debug/net12.0/Microsoft.Maui.Controls.SourceGen.UnitTests.dll Passed: 1016/1016
dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj Passed: 7465, 30 skipped
dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj (sets MauiXamlTrimmableStyles=true, so its SourceGen fixtures use lazy styles) Passed: 2331, 8 skipped
dotnet msbuild -getProperty:MauiXamlTrimmableStyles on a project importing Microsoft.Maui.Controls.Common.targets '' without PublishAot, true with -p:PublishAot=true, false with an explicit override
npx cspell --config ./eng/automation/cspell/cSpell.json "docs/**/*.md" Passed: 0 issues
git diff --check Passed

The new LazyStyleKeepsSettersReplacedBeforeInitialization test failed before the Hot Reload fix (3 setters instead of 1, and a removed setter was still applied).

Trimming check. A console app references this branch's Microsoft.Maui.Controls build and has three styles: an implicit style for a control it creates, one for a control it never creates, and an {x:Static}-typed style as an eager baseline. Symbols for the unused control and its setter's payload type in the NativeAOT map file (dotnet publish -c Release -r osx-arm64, PublishAot=true):

Unused control Its setter's payload
MauiXamlTrimmableStyles=true 2 (type descriptor only) 0
MauiXamlTrimmableStyles=false 13 2

The used style is applied in both cases. With ILLink (PublishTrimmed=true, TrimMode=full, no AOT), the unused control's .cctor and accessors and the payload type all survived, the same as for the eager baseline. This is a small sample, not a full MAUI app.

Not yet validated:

  • CI on this head.
  • UI and device tests. With the new default they run with eager styles unless the test app sets PublishAot.
  • Size measurements in a real NativeAOT MAUI app.

Issues Fixed

Contributes to #33156 as part of the full-trimming work; this PR alone is not the complete solution.

@simonrozsival simonrozsival changed the title [WIP] Trimmable/Lazy Styles for SourceGen [WIP][XSG] Trimmable/Lazy Styles for SourceGen Jan 16, 2026
@simonrozsival
simonrozsival force-pushed the dev/simonrozsival/trimmable-styles branch from bfcfe86 to 01cf3de Compare January 16, 2026 13:21
@simonrozsival simonrozsival changed the title [WIP][XSG] Trimmable/Lazy Styles for SourceGen [WIP][net11.0][XSG] Trimmable/Lazy Styles for SourceGen Jan 16, 2026
@simonrozsival
simonrozsival changed the base branch from main to net11.0 January 16, 2026 13:22
@simonrozsival simonrozsival added xsg Xaml sourceGen perf/app-size Application Size / Trimming (sub: perf) labels Jan 16, 2026
@simonrozsival
simonrozsival force-pushed the dev/simonrozsival/trimmable-styles branch 6 times, most recently from 64a71d2 to eab10eb Compare January 16, 2026 14:48
@simonrozsival simonrozsival changed the title [WIP][net11.0][XSG] Trimmable/Lazy Styles for SourceGen [net11.0][XSG] Trimmable Styles Jan 20, 2026
@simonrozsival
simonrozsival marked this pull request as ready for review January 20, 2026 12:47
Copilot AI review requested due to automatic review settings January 20, 2026 12:47

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.

Pull request overview

This PR implements lazy/trimmable styles for XAML Source Generation, enabling the IL trimmer to remove unused styles and their target types from compiled apps. The feature addresses issue #33156 by deferring style initialization until first application and using string-based type names instead of Type objects for AOT compatibility.

Changes:

  • Added new Style(string assemblyQualifiedTargetTypeName) constructor and LazyInitialization property for deferred initialization
  • Modified IStyle.TargetType to be nullable (Type?) to support trimmed types
  • Updated source generator to emit lazy style initialization code with type guards
  • Extended visitor infrastructure with StopOnStyle, VisitNodeOnStyle, and IsStyle methods across all visitors (both SourceGen and XamlC)

Reviewed changes

Copilot reviewed 47 out of 47 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
Style.cs Adds lazy constructor, LazyInitialization property, nullable TargetType resolution, and TargetTypeFullName for trim-safe type comparison
IStyle.cs Changes TargetType to nullable Type? to support trimmed types
MergedStyle.cs Updates to handle nullable TargetType from IStyle
ResourceDictionary.cs Uses TargetTypeFullName instead of TargetType.FullName for adding styles
CreateValuesVisitor.cs Implements TryCreateTrimmableStyle to generate string-based Style constructor
SetPropertiesVisitor.cs Generates LazyInitialization lambda with type guard before style property assignment
SetNamescopesAndRegisterNamesVisitor.cs Adds null checks for nodes not in Variables dictionary (Style content)
XamlNode.cs Implements IsStyleContent logic for skipping Style children during normal traversal
XmlName.cs Adds _StyleContent marker for identifying styles needing lazy initialization
All visitor files (20+) Implements StopOnStyle, VisitNodeOnStyle, and IsStyle interface methods
PublicAPI files (7) Adds new public API entries for Style constructor and LazyInitialization setter
Test files (10+) Updates tests to call InitializeIfNeeded for SourceGen inflator, adds comprehensive lazy style tests

Comment thread src/Controls/src/Core/Style.cs Resolved
Comment thread src/Controls/src/Core/Style.cs Resolved
@simonrozsival
simonrozsival force-pushed the dev/simonrozsival/trimmable-styles branch from e7d801f to d0c0ce4 Compare January 20, 2026 13:31
@rmarinho

Copy link
Copy Markdown
Member

/rebase

@simonrozsival

Copy link
Copy Markdown
Member Author

@copilot this PR needs a proper rebase with conflict resolution. open a PR which addresses this issue. make sure it is up to date with the base net11.0 branch.

Copilot AI commented Feb 12, 2026

Copy link
Copy Markdown
Contributor

@simonrozsival I've opened a new pull request, #34011, to work on those changes. Once the pull request is ready, I'll request review from you.

@simonrozsival
simonrozsival force-pushed the dev/simonrozsival/trimmable-styles branch from 3536086 to fefc63a Compare February 13, 2026 08:22
simonrozsival added a commit that referenced this pull request Feb 18, 2026
…hanges

These changes belong in separate PRs:
- #33611 (CSS StyleSheet trimming)
- #33561 (EventTrigger trimming)
- #33160 (HybridWebView trimming)

Reverted files to their main branch state, keeping only the
[ElementHandler] attribute addition on HybridWebView.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@StephaneDelcroix
StephaneDelcroix force-pushed the dev/simonrozsival/trimmable-styles branch from fefc63a to 59a9982 Compare February 27, 2026 15:27
@github-actions

This comment has been minimized.

Only NativeAOT removes the setters behind the generated `is T` check.
ILLink keeps them: a trimmed (non-AOT) publish kept the unused style's
control and payload, just like an eager style. So
MauiXamlTrimmableStyles now defaults to $(PublishAot), and the
generator creates eager styles when the property is not set.

Generated styles now use `new Style(typeof(T))`. With NativeAOT,
typeof(T) keeps only T's type descriptor (316 bytes in the sample app)
and the guarded setters are still removed. This drops the
Style(string) constructor, Type.GetType and its IL2057 suppression,
the nullable TargetType and name-based matching. Implicit-style keys
stay strings.

Fix Hot Reload replacing the setters of a lazy style that has not been
applied yet: its first apply added the stale XAML setters back. The
initializer's setters are now discarded in that case; its triggers and
behaviors are kept.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@simonrozsival
simonrozsival force-pushed the dev/simonrozsival/trimmable-styles branch from 9e047dc to 144cbed Compare November 26, 2026 13:44
…spec

Setting PublishAot for only some configurations is an app configuration
choice, not something this feature needs to document.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@simonrozsival simonrozsival changed the title [net12.0][XSG] Trimmable Styles [XSG] Trimmable Styles Nov 26, 2026
@simonrozsival

This comment has been minimized.

@azure-pipelines

This comment has been minimized.

@simonrozsival
simonrozsival marked this pull request as ready for review November 26, 2026 16:30
@simonrozsival

Copy link
Copy Markdown
Member Author

CI on c403deb12e is red only because of failures that already exist on main at the base commit f38825f543. All of them also fail on main:

  • maui-pr, Windows build and Samples windows: CS0260 in TestCases.HostApp/Issues/Issue17521.cs and Issue33356.cs, plus Essentials device-test build errors. main fails the same way in 1701052 and 1700930.
  • maui-pr, RunOniOS_MauiReleaseTrimFull_CoreCLR: IL2121 in QueryPropertyConversion.cs, identical on main.
  • maui-pr-uitests, all legs: the UI test project doesn't build (RS1038 in UITest.Analyzers/NUnit/NUnitTestMissingCategoryAnalyzer.cs), so no UI tests ran. main's 1701137 fails the same way.
  • maui-pr-devicetests:
    • Windows has the same Essentials build errors.
    • Android, iOS and Mac Catalyst fail the same tests as main's 1701071, with the same test totals. The exception is one extra Mac Catalyst failure, Changing the destination's Opacity during a flight doesn't reveal it under the snapshot (a page-transition test that timed out). It also fails on Android in both runs and on main's Mac Catalyst runs 1700957 and 1700876.

UI tests haven't run on this PR yet. I'll re-run them once main builds again.

@simonrozsival
simonrozsival requested review from kubaflo and a balanced review from Copilot and removed request for Copilot November 26, 2026 16:30
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@azure-pipelines

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 26, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Warning

Your /review couldn't start due to a transient error triggering the pipeline. The command was left unacknowledged so scheduled recovery can retry it automatically; you can also comment /review again in a minute.

@github-actions github-actions Bot removed the s/agent-review-in-progress AI review is currently running for this PR label Nov 26, 2026
- Don't assign fields for x:Name inside a Style. Code-behind declares
  no field for them, so SetFieldsForXNamesVisitor emitted an
  assignment to a missing field (CS1061) for eager styles. With
  trimmable styles the generator crashed instead, because the style
  content is created later inside the lazy initializer.
- Roll back setters, triggers and behaviors added by an initializer
  that throws, so a later apply doesn't duplicate them.
- Keep XAML-declared triggers and behaviors ahead of ones added from
  code, as already done for setters.

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

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

Unresolved issues can leave null-valued platform setters, apply styles after removal, resolve TargetType in the wrong namespace scope, and emit misleading target-type warnings.

4 open issues
1 file not reviewed
  • src/Controls/src/SourceGen/xlf/MauiGResources.Designer.cs: Generated file

Review effort: Balanced

if (string.IsNullOrEmpty(targetType))
return null;

return TypeArgumentsParser.ParseSingle(targetType, namespaceResolver, lineInfo);
Comment on lines +323 to +324
if (!_targets.TryGetValue(bindable, out _))
return;
Comment on lines +341 to +345
// For Setters, only inline-initialized instances should call TryProvideValue; otherwise
// the normal property assignments should remain intact.
var isInlineInitializedSetter = IsInlineInitializedSetter(node, out var isSetter);
if (!isSetter || isInlineInitializedSetter)
node.TryProvideValue(Writer, Context, getNodeValue);
Comment on lines +69 to +70
if (resource is null || !resource.IsStyle(Context))
return;
@kubaflo
kubaflo merged commit 04d3696 into main Nov 26, 2026
11 of 17 checks passed
@kubaflo
kubaflo deleted the dev/simonrozsival/trimmable-styles branch November 26, 2026 20:46
@simonrozsival

Copy link
Copy Markdown
Member Author

The validation-only PR #40667 surfaced a possible lazy-style visual regression that should not be dismissed as a pre-existing failure:

This is evidence for investigation, not yet proof that lazy styles caused the visual difference: the control is a different source snapshot, and the screenshot attachments have not been compared here. No baseline images were changed. The latest full UI run is still in progress, so this is not an all-clear.

kubaflo added a commit that referenced this pull request Nov 30, 2026
<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `cdeafb72937dc746d00866464afe6553904c7d9f`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 7/10 | ↑ Two review rounds addressed:
most-specific interface resolution, plus Hot Reload replacement of
attribute and default handlers (scoped per app, reinstalled after
removal). Each fix has tests that fail without it.<br>↑ Rebased onto the
reviewed lower layers. Core 1,279 tests pass under dotnet test and
xunit.console, and Controls 7,532 pass. Controls compiles for Android,
iOS and MacCatalyst.<br>↑ The new Android compatibility-renderer default
activation device test passes 3/3 on an emulator.<br>↓ CI and the full
device suites on this head are not yet assessed.<br>↓ Windows paths are
compile-only; no Windows device coverage is added. |
<!-- /copilot-assessment -->

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

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### 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).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change

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

Follow-up to #28357 targeting **main / .NET 12**. Rebased onto the
trimmable-styles merge (#33561),
`04d36966ed9d334c056872d83741e973d61f6c55`.

#### Stack

This PR is **layer 4 of 5** in a stack split from the original single PR
for easier review. It is based on #40728, and its own diff covers only
the attribute-based resolution:

1. #40721: context-aware handler activation and Hot Reload type
matching.
2. #40725: mapper infrastructure that preserves app customizations, the
`*ForControls` remap helpers and sealed framework mappings.
3. #40728: lazy Controls mapper remapping on first handler attachment.
4. **This PR**: `[ElementHandler]` attributes on Controls types, removal
of the eager default DI registrations, resolution precedence and caches,
Hot Reload cache invalidation, Material3 and Apple Shell attribute
selection, Windows `PreventGestureBubbling` overrides and the
constructor-argument diagnostic.
5. #40715: Copilot guidance for working with handlers and mappers.

The sections below describe the combined feature; the activation, mapper
and lazy-remap sections are reviewed in layers 1–3. The combined tree is
unchanged from the reviewed `5db8263312bf8ea352e8f5a40b04e148c235f4cc`
except for the follow-up below.

Built-in Controls primarily declare `[ElementHandler]` instead of being
rooted by an eager default DI registration table. Controls-specific
mapper changes run lazily when handlers attach, while preserving
recorded application customizations. Open review items are listed below;
this description is not a merge-readiness approval.

#### Attribute-based handler resolution

`ElementHandlerAttribute` remains internal. The concrete handler type is
statically referenced for trimming/AOT. Although the attribute has
`Inherited = false`, the factory explicitly walks the base-type
hierarchy for fallback. Nested control-specific attributes preserve
conditional Android Material3 selection and Windows CollectionView
handler selection without unconditionally referencing both alternatives
on the active path.

`GetHandler(Type)` and `GetHandlerType(Type)` share the resolution
order:

1. Exact DI registration.
2. Attribute declared directly on the requested type.
3. The more specific of the nearest registered base class and the
nearest inherited attribute. An inherited attribute ranks like the
built-in registration its declaring class used to have; a registration
on that class or a subclass wins.
4. The most specific registered interface. With Controls defaults on,
the `IContentButton`/`IContentView` defaults compete here as interface
registrations.
5. Content interface fallbacks: `IContentButton` →
`ContentButtonHandler`, then `IContentView` → `ContentViewHandler`.

A conditional attribute can declare no handler, for example Apple
`ShellItem` when `UseiOSShellHandler` is off; resolution then continues
as if it were absent. An exact `AddHandler` still overrides defaults. A
registration for `Button` applies to an unannotated `FancyButton :
Button`, but registering `IButton` or `View` does not divert it from
`ButtonHandler`. Factory registrations remain authoritative even when
`GetHandlerType` cannot report an `ImplementationType` and therefore
returns `null`.

Controls enables an `ElementHandlerDefaultsEnabled` policy per app's
handler collection: `TryAddHandler` does not replace a directly declared
default or the `IContentButton`/`IContentView` defaults, but still
registers custom derived types that only inherit an attribute fallback.
Apps without Controls defaults retain normal `TryAddHandler` behavior;
`AddHandler` always remains an override. `UseMauiApp` enables the policy
before registration callbacks execute regardless of builder-chain order.
`AddMauiControlsHandlers` remains a non-obsolete compatibility no-op
returning the original collection, without enabling defaults or eagerly
remapping controls.

#### Cache ownership and invalidation

Only attribute and assignable-registration lookups are cached. The
complete resolution result and constructor-activation strategy are
**not** cached; current registrations and delegates are consulted on
every request, and transient requests create fresh handlers.

Each factory owns its resolution caches and builds its assignable index
from current descriptors, including raw DI registrations. Built-in
collection mutations (`Add`, `Insert`, indexer replacement, `Remove`,
`RemoveAt`, `Clear`) advance a version. Hot Reload metadata updates,
cache clearing, replaced-view callbacks and reset advance a checked
generation before views are recreated. Hot Reload registration
replacement also changes the collection version. A new cache generation
replaces the old dictionaries, preventing concurrent old-generation
readers from repopulating new state. Custom collections without mutation
tracking do not retain resolution caches.

Descriptor lookup stays consistent with indexer/list changes; removing
the last registration restores the preceding descriptor for that service
type. Cache lookup supports concurrent readers, but collection mutation
retains the standard `IServiceCollection` contract and must not run
concurrently with resolution.

#### Context-aware activation without an activation cache

`ElementExtensions.ToHandler` delegates reflection-based construction to
the factory. A public parameterless constructor is preferred when
present; otherwise `ActivatorUtilities.CreateInstance` resolves
dependencies from the current context (including its Android context).
Value-type handlers keep default construction. The constructor-presence
check avoids using `MissingMethodException` as ordinary control flow,
including first activation, without additional cache
ownership/invalidation complexity.

Direct public `GetHandler` callers retain parameterless-constructor
behavior. Custom factories retain their existing exception-based
injection fallback. Dependency failures propagate without retrying the
entire injection. Factory activation still uses the current service
provider/`IMauiContext`, and activated factory types participate in Hot
Reload replacement.

Historical matched **.NET 11** managed Release microbenchmarks measured
warm injected activation at roughly 9 µs with exception-first
construction versus 0.10–0.16 µs when missing-constructor exceptions
were avoided. Constructor checks were comparable to a factory-owned
activation cache; shared-host noise prevents claiming a small difference
between those alternatives. These are **not .NET 12 measurements,
Android startup claims, or APK-size results**.

#### Lazy mapper remapping and main integration

Controls `Element.SetHandler` invokes the remap hook before attaching
any handler, including compatibility renderers.
`ElementHandler.SetVirtualView` also invokes it for direct attachment
outside Controls. Each remappable type calls its base hook and owns a
blocking one-time initialization action; unrelated controls do not share
a global initialization lock.

Built-in mapper declarations seal their initial framework mappings.
Controls property/command remaps update those mappings underneath
recorded app customizations, preserving direct indexer overrides and
`AppendToMapping`, `PrependToMapping`, `ModifyMapping`, and
`ReplaceMapping` in registration order, including keys that are absent
until a lazy remap and keys inherited from chained mappers. See
`docs/design/HandlerResolution.md` for the ordering rules.
Command-property dependency setup remains in control initialization,
independent of handler attachment.

The main rebase preserves newer upstream functionality:

- `ContentButton` has its own handler attribute, `IContentButton`
fallback, sealed mapper and lazy Android ripple remapping.
- Switch OnColor remapping uses the lazy hook and
customization-preserving prepend behavior on Apple platforms.
- Android toolbar drawer-toggle remapping and the current
Android/Windows common-mapping scope are retained.
- RoundRectangle retains `IShapeWithStroke`; Shell retains the
reentrant-navigation unsubscribe fix; handler instrumentation is
preserved.
- Android ListView/TableView/Frame compatibility attributes retain
context-accepting activation through the factory's current-context
injection path.
- HybridWebView remains a deferred factory registration. Cell attributes
retain their platform scopes, and Windows CollectionView feature-switch
selection remains conditional.
- Controls navigation-transition hooks are installed independently of
the removed eager remapping helper.

Obsolete eager registration/remapping helpers and
Android-context-specific handler interfaces/attributes are removed.
Detailed resolution and activation contracts are documented in
`docs/design/HandlerResolution.md`.

#### Updated Android APK measurements (.NET 12)

**Trimmable styles + handlers reduce the plain template's signed
NativeAOT APK by 756 KiB (4.64%) compared with neither optimization.**
Since styles are already merged into main, this PR's incremental saving
over styles alone is **712 KiB**. The 4.64% figure is the combined
effect, not a handlers-only measurement.

| Framework state | NativeAOT APK (bytes) | Release/CoreCLR APK (bytes)
|
| --- | ---: | ---: |
| Neither styles nor handlers | 16,686,161 | 18,591,480 |
| Trimmable styles only | 16,641,105 | 18,591,480 |
| Trimmable styles + handlers | 15,912,017 | 18,398,968 |

Styles alone save 44 KiB with NativeAOT. Ordinary Release/CoreCLR saves
**188 KiB (1.04%)** with handlers; styles alone do not change that APK's
size under its default settings.

Measured the same unmodified `dotnet new maui -n Template --framework
net12.0` source, **without `--sample-content`**, as signed ARM64 APKs.
Framework revisions were `f38825f543a18fdcf5ac672b73835e50edd159f6`
(neither), `04d36966ed9d334c056872d83741e973d61f6c55` (styles), and
`9d2e9cf9b649b647777ec885cd31d1e303e3d49e` (both).

The matched local builds use SDK `12.0.100-alpha.1.26523.103`, Android
workload `37.99.0-preview.1.358`, and the same MAUI package version
`12.0.0-pr29952.local`, with separate feeds/caches. Non-MAUI
dependencies, runtime native libraries, signing key, app source and
relevant build settings were matched and package hashes checked.
NativeAOT uses full trimming and default trimmable styles; ordinary
Release uses CoreCLR, partial trimming and default composite R2R. Both
retain the SDK's default trimmable typemap and shipped/default profile
policy: **no app-trained or custom MIBC**.

These are APK file-size measurements, **not startup/JIT/runtime
measurements**. No handlers-only arm was measured; the incremental
handler saving includes its interaction with merged styles.

Local artifact build commands (all **passed**): `bash
artifacts/apk-styles-handlers-20261126/build-app.sh baseline aot`, `bash
artifacts/apk-styles-handlers-20261126/build-app.sh none aot`, `bash
artifacts/apk-styles-handlers-20261126/build-app.sh both aot`, and the
same three commands with `release` instead of `aot`. The historical
directory name `none` contains the styles-only revision; provenance is
checked against `source.sha`, not inferred from directory labels.
`python3 artifacts/apk-styles-handlers-20261126/measure.py` —
**passed**; verifies all six APKs and records exact
source/settings/package/profile identities in `results.json` alongside
retained commands, logs and binlogs. These scripts and outputs are local
investigation artifacts, not files added by this PR.

#### Local validation after the styles rebase (9d2e9cf)

The latest English-locale `net12.0` runs passed:

- `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test
src/Core/tests/UnitTests/Core.UnitTests.csproj -c Release
-p:MauiPlatforms= -m:1 -v:q` — **1,198 passed**.
- `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c
Release -p:MauiPlatforms= -m:1 -v:q` — **7,522 passed, 30 skipped**.
- `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj -c
Release -p:MauiPlatforms= -m:1 -v:q` — **910 passed, 71 skipped**.

The previously reported comma-decimal failures were independently
reproduced on clean main and pass with the English locale; they are not
this PR's regressions. Existing coverage includes collection
mutation/raw registrations, custom unversioned collections, metadata and
handler replacement, context/app isolation, dependency errors without
retry, constructor preference/value types, first-use exception
elimination, recorded mapper customization and ContentButton
activation/type lookup.

Local Android framework packaging and the six trimmed/NativeAOT template
builds above passed. This does **not** establish device/UI behavior or
iOS/MacCatalyst/Windows validation for this head; CI attribution and
remaining review findings are still being assessed.

#### Review follow-up in 714715d

- **Handler precedence:** An inherited attribute ranks like the built-in
registration its declaring class used to have. The most specific
concrete candidate wins, and registered concrete types outrank
interfaces. With Controls defaults on, `IContentButton`/`IContentView`
defaults compete as interface registrations, and `TryAddHandler` no
longer replaces them.
- **Mapper customizations:** Lazy Controls remaps now compose underneath
app customizations, as if they had run at startup. This covers post-seal
assignments to absent keys, child customizations of parent keys that
only appear in a later lazy remap, and delegates read before a remap.
App-created mapper chains keep capture-at-customization semantics, and
wrapping a mapping read from a mapper no longer recurses.
- **Apple Shell:** `UseiOSShellHandler` again selects `ShellHandler` or
`ShellRenderer`, along with the item, section and content handlers.
Conditional attributes may declare no handler, so inactive handlers
remain trimmable.
- **CI fixes:** Hot Reload handler replacement matches by type name;
xunit.console loads the test assembly twice. The Material3 Picker
expectation is corrected, there is a blocking
`OneTimeInitializationAction` test, and the constructor-argument
diagnostic is clearer.

Validation: Core unit tests passed 1,223/1,223 under `dotnet test` and
xunit.console with `DOTNET_MODIFIABLE_ASSEMBLIES=debug`. Controls unit
tests passed 7,530, with 30 skipped. `Controls.Core` compiles for
`net12.0-ios27.1` and `net12.0-maccatalyst27.0`. The new Shell
resolution device tests passed 2/2 on MacCatalyst via
`.github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project
Controls -Platform maccatalyst -TestFilter "Category=Shell"
-IncludeClasses
"Microsoft.Maui.DeviceTests.ShellHandlerResolutionTests"`. Android and
iOS device runs and CI are not yet assessed on this head, and the APK
measurements above predate it.

Follow-up in 5db8263: lazy RadioButton (Android) and TabbedPage remaps
keep a `PlatformViewFactory` the app sets during startup. Resolution
fetches its cache once per request, and the typed `*ForControls` mapper
helpers check view and handler types before casting.

Follow-up when splitting the stack:
- Restores the iOS/MacCatalyst `UpdateCollectionViewAccessibilityTraits`
refresh on semantics changes. A rebase in 7fba985 had accidentally
dropped it.
- `VisualElementMapperTests` trigger the lazy remap before reading
global mapper keys. They previously passed only when another test had
attached a handler first.
- `HandlerResolution.md` gains the lower layers' more precise activation
and remapping text.

Validation on `c1de79de46`:
- Core unit tests: 1,225 passed under `dotnet test` and xunit.console.
- Controls unit tests: 7,530 passed, 30 skipped.
- The three mapper key-order tests pass when run on their own.
- `Controls.Core` compiles for `net12.0-android37.0`, `net12.0-ios27.1`
and `net12.0-maccatalyst27.0`.

Review follow-up (rebased; now in cdeafb7):
- **Interface resolution:** resolution now picks the most specific
matching interface before reporting an ambiguity. A concrete
`IContentButton` with `IButton` and `IContentView` registered resolves
to `ContentButtonHandler`, or to a registered `IContentButton` handler.
Unrelated registrations remain ambiguous.
- **Hot Reload:** pending handler replacements also apply to handlers
resolved from `[ElementHandler]` or the content interface defaults.
These have no collection descriptor, so the replacement is registered
for the requested view type the next time it is resolved.
- **Lower layers:** this PR was rebased onto #40728. That carries the
lower layers' review fixes: injected handlers are never retained as
singletons, the mapper fixes, and Label's public appends are back at
type initialization. HandlerResolution.md now has a combined "Behavior
changes" section with migration guidance.

Second review round:
- **Hot Reload:** replacements of attribute and default handlers apply
only to the collection passed to `RegisterHandlers`. A newly registered
collection receives replacements that were already applied to the
previous one, and a replacement whose registration was removed is
installed again.
- **Registration order:** HandlerResolution.md documents the changes.
`AddHandler` before `UseMauiApp()` now wins, `AddMauiControlsHandlers()`
no longer restores a replaced handler, and `RemoveAll` followed by
`TryAddHandler` no longer replaces an attributed default (use
`AddHandler`).
- **Android device test:** `CompatibilityRendererDefaultActivationTests`
covers default activation of the `ListView`, `TableView` and `Frame`
renderers with the current Android `Context`.

Validation on `cdeafb7293`:
- Core unit tests: 1,279 passed under `dotnet test` and xunit.console.
- Controls unit tests: 7,532 passed, 30 skipped.
- `Controls.Core` compiles for Android, iOS and MacCatalyst.
- The Android device test above passed 3/3.

Earlier validation on `a0f29fdbde`:
- Core unit tests: 1,271 passed under `dotnet test` and xunit.console.
- Controls unit tests: 7,531 passed, 30 skipped.
- `Controls.Core` compiles for `net12.0-android37.0`, `net12.0-ios27.1`
and `net12.0-maccatalyst27.0`.

#### Behavior changes

- **`AddMauiControlsHandlers()`:** Remains a compatibility no-op.
Calling it after registering a custom handler, for example
`AddHandler(typeof(Button), typeof(CustomButtonHandler))`, no longer
restores `ButtonHandler`. Remove the custom registration instead.
- **Custom `IMauiHandlersFactory` implementations:** Not supported.
Built-in defaults are resolved from attributes by the built-in factory,
not exposed as descriptors in `IMauiHandlersCollection`, so a
replacement factory can no longer resolve Controls views. A follow-up
will discourage and eventually remove this extension point.
`IMauiContext.Handlers` exposes the interface, so this needs a
replacement design rather than just `[Obsolete]`.
- **Lazy remaps:** Controls mapper remaps run on each control type's
first attachment instead of at `UseMauiApp`. App customizations made
during startup are preserved as described above. Label keeps its pre-PR
timing: its remaps already ran lazily from its static constructor.

Windows CollectionView, ListView and TableView device coverage is left
to the Windows controls maintainers.

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

Supports the trimmable handler work started in #28357.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

---------

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 Dec 1, 2026
… remove unused handlers (#40952)

<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `104dba74af898b0de2de5ecb752be7e1186d07b1`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8/10 | ↑ Android NativeAOT template app: APK
−204,800 B, .so −584,048 B (98% of the unused-styles-deleted
ceiling).<br>↑ Emulator screenshot (API 35) pixel-identical to main; no
crash or style warning.<br>↑ Style tests: Controls.Core 255/255, Xaml
100/100, SourceGen 964 passed / 0 failed.<br>↓ Only one app (the
template) measured; iOS/Mac Catalyst NativeAOT not measured.<br>↓ CI not
yet run. |
| Diagnosis confidence | 9/10 | ↑ ILC scan DGML on main shows
ActivityIndicator type metadata plus the get_CustomAttributes
conditional node leading to the handler ctor; with this change
ActivityIndicatorHandler has 0 nodes (350 on main).<br>↑ A console
NativeAOT probe reproduces the retention with typeof and its removal
with a string. |
| Evidence fit | 9/10 | ↑ The removed handlers (ActivityIndicator,
DatePicker, Picker, Slider, Switch, TimePicker, RefreshView,
SwipeItemMenuItem) are exactly the unused style targets in the
template's Styles.xaml. |
<!-- /copilot-assessment -->

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

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### 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).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change

Trimmable styles (#33561) generate a style whose setters are behind an
`is T` check, so NativeAOT can remove them when `T` is never
instantiated. The merged version creates the style with `new
Style(typeof(T))`, on the assumption that `typeof(T)` only keeps a small
type descriptor. In a MAUI app it keeps much more:

1. `typeof(T)` (`ldtoken`) gives `T` reflection metadata in NativeAOT.
2. `MauiHandlersFactory.FindElementHandlerAttributes` calls
`GetCustomAttribute<ElementHandlerAttribute>()`, so ILC keeps the
`[ElementHandler]` attribute on every type that has metadata.
3. The attribute's constructor parameter and `GetHandlerType()` are
annotated `[DynamicallyAccessedMembers(PublicConstructors)]`, so the
handler's constructors are kept, and with them its mappers and platform
code (both Handler and Handler2 when `UseMaterial3` is unset).

So every style target in `Styles.xaml` keeps its handler, even when the
app never uses the control.

This PR goes back to the earlier design from #33561: generated styles
use `new Style("Namespace.Type, Assembly")` for non-generic targets.
Generic targets keep `typeof(T)`, because their assembly-qualified names
depend on reference assemblies. The Hot Reload fix and the
`MauiXamlTrimmableStyles` = `PublishAot` default from the merged version
are kept.

Changes:
- `Style(string assemblyQualifiedTargetTypeName)` constructor,
`[EditorBrowsable(Never)]`.
- `Style.TargetType` resolves the name lazily with `Type.GetType`
(IL2057 suppressed).
- Style matching, implicit-style keys (`ResourceDictionary`) and the
mismatch warning use the target type's full name.
- `IStyle.TargetType` is nullable; `MergedStyle` and `BasedOn`
validation handle null.
- The source generator emits the assembly-qualified name
(`CreateValuesVisitor`, `ISymbolExtensions.GetAssemblyQualifiedName`).
- `docs/trimmable-styles-spec.md` explains why `typeof` is not used.

#### Size (plain `dotnet new maui`, Release, net12.0-android,
android-arm64, `PublishAot=true`)

| Build | Signed APK (B) | libTrimProbe.so (B) |
|---|---|---|
| main (`typeof`) | 16,030,802 | 20,727,560 |
| **This PR** | **15,826,002 (−204,800)** | **20,143,512 (−584,048)** |
| main with unused styles deleted from Styles.xaml (ceiling) |
15,821,906 | 20,115,936 |

The handler constructors of ActivityIndicator, DatePicker, Picker,
Slider, Switch, TimePicker, RefreshView and SwipeItemMenuItem are gone
from the map. In the ILC scan graph, `ActivityIndicatorHandler` appears
0 times (350 on main) and `ActivityIndicator` has no metadata node.

#### Tradeoffs

- New hidden public API: `Style(string)` (added to
`PublicAPI.Unshipped.txt`). Runtime-inflated XAML, XamlC, Hot Reload and
user code keep using the `Type` constructor.
- `Type.GetType` on a string needs an IL2057 suppression and costs a
one-time lookup on first `TargetType` read.
- `Style.TargetType` can be `null`, but only for a generator-created
style whose target type was trimmed away (that style can never be
applied).

Alternatives considered: a generic `Style<T>` still keeps the handler
(its `TargetType => typeof(T)` keeps metadata), and keying styles
without any `Type` would break the public `Style.TargetType`.

Possible longer-term follow-up: make handler discovery independent of
type metadata (instead of `GetCustomAttribute` +
`DynamicallyAccessedMembers` on `[ElementHandler]`). That would also
stop other `typeof(Control)` uses (`DataTemplate`, `x:Type`,
`BindableProperty` owner types) from keeping whole handlers.

#### Validation

- Published the template app with Android NativeAOT using packages built
from this branch; sizes above.
- Ran it on an API 35 arm64 emulator: cold start OK, screenshot
pixel-identical to main, no crash, no "Style TargetType ... is not
compatible" warning.
- `dotnet test
src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj
--filter "FullyQualifiedName~Style"`: passed (255/255).
- `dotnet test
src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj
--filter "FullyQualifiedName~Style"`: passed (100/100).
- `dotnet test
src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`:
passed (964 passed, 0 failed); 4 assertions updated to expect the
assembly-qualified name.
- Not run: iOS/Mac Catalyst NativeAOT size comparison.

### Issues Fixed

Follow-up to #33561. No separate issue filed.

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, keep "Allow edits by maintainers" on so the agent can
push to your branch; otherwise it opens a follow-up PR that keeps your
commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

Co-authored-by: Copilot App <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

do-not-merge Don't merge this PR perf/app-size Application Size / Trimming (sub: perf) s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) xsg Xaml sourceGen

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants