Skip to content

Subscribe orientation and rotation state triggers to DeviceDisplay weakly - #40453

Merged
kubaflo merged 3 commits into
dotnet:candidate/11.0.1xx-sr2from
MykhailoDav:fix-40450-state-trigger-display-leak
Nov 20, 2026
Merged

kubaflo merged 3 commits into
dotnet:candidate/11.0.1xx-sr2from
MykhailoDav:fix-40450-state-trigger-display-leak

Conversation

@MykhailoDav

Copy link
Copy Markdown
Contributor

Description of Change

OrientationStateTrigger and DisplayRotationStateTrigger subscribe to the static DeviceDisplay.MainDisplayInfoChanged when attached and unsubscribe when detached. Triggers only detach when the element's window changes, and Window.Destroying doesn't clear Page. So when Android recreates the Activity, the old page keeps its window, its triggers stay subscribed, and the static event keeps the whole old page alive (trigger → VisualState → setters → old page). Every recreation leaks another page, and the dead triggers keep reacting to rotation.

The triggers now subscribe through a new WeakDisplayInfoChangedProxy, built like the existing WeakNotifyCollectionChangedProxy in WeakEventProxy.cs. Each trigger keeps its handler in a field, because the proxy only holds it weakly. A proxy whose trigger was collected removes itself on the next display change. Unlike VisualElement and Border, the triggers don't unsubscribe from a finalizer: removing the last handler stops the platform display listeners, which shouldn't happen on the finalizer thread.

FlyoutPage has a similar static MainDisplayInfoChanged subscription; I left it out of this PR.

Tests

New tests in OrientationStateTriggerTests and DisplayRotationStateTriggerTests (Controls.Core.UnitTests):

  • AttachedTriggerDoesNotKeepPageAlive keeps a page with the trigger in a window that is never torn down and checks that the page can be collected. Without the fix both fail with "Page should not be alive!".
  • TriggerStillUpdatesAfterGarbageCollection forces a GC and checks that the trigger still reacts to a display change. It fails if the handler isn't kept alive by the trigger.

The trigger tests go from 32/34 to 34/34. The full Controls.Core.UnitTests run has the same single failure as clean net11 (TwoWayBindingToNullableDoublePropertyWithEmptyStringBecomesNull, a decimal-comma locale issue on my machine).

Before / after (sandbox app, Android emulator API 37, Release): the issue's XAML plus a "Collect and count" button that counts pages still alive. The Activity is recreated three times by changing the font scale.

Before: all 4 pages are still alive After: only the current page is alive
before after

Full clips: before.mp4 · after.mp4. The after clip also rotates the emulator to show the landscape template still switches.

Not checked: iOS, Mac Catalyst and Windows (shared code, not run there), Debug builds and a physical device.

Issues Fixed

Fixes #40450

kubaflo and others added 3 commits November 19, 2026 19:25
…r/DragLeave (dotnet#40441)

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

On iOS, `DragEventArgs.GetPosition()` can throw a
`NullReferenceException` inside a `DragOver` or `DragLeave` handler. The
exception crashes the app.

**CI evidence.** The `DropEventCoordinates` UI test crashed the HostApp
on both attempts on the iOS CoreCLR lane of SR2 candidate dotnet#40116
(maui-pr-uitests
[1690394](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1690394),
iOS latest Editor..Fr job). The job's `.ips` reports show SIGABRT from
`xamarin_process_managed_exception` under `-[UIDropInteraction
_dragDestinationGestureStateChanged:]`. The logarchive shows the managed
exception:

```
System.NullReferenceException
  at DragAndDropDelegate.CalculatePosition(IElement, WeakReference, WeakReference)
  at DragAndDropBetweenLayouts.OnDragOver(...)        // HostApp calls e.GetPosition(...)
  at DragAndDropDelegate.<HandleDragOver>...
  at DragAndDropDelegate.SendEventArgs(...)
  at DragAndDropDelegate.HandleDragOver(...)
  at DragAndDropDelegate.SessionDidUpdate(...)
```

**Root cause.**
- `SessionDidUpdate` and `SessionDidExit` pass
`session.LocalDragSession`, a transient managed wrapper of the native
local drag session, into `HandleDragOver` and `HandleDragLeave`.
- Those methods put only a `WeakReference` to it in the `GetPosition`
callback, and nothing else on the path keeps it alive:
`PlatformDragEventArgs` holds the outer `IUIDropSession`, not the local
drag session.
- A GC while the user's handler is running can therefore collect the
wrapper. `CalculatePosition` then calls `LocationInView` on a null
session.
- Separately, `HandleDragOver` built a weak reference even when
`LocalDragSession` is null (a drag from another app), so `GetPosition`
always threw in that case. `HandleDragLeave` and `HandleDrop` already
return null there.

The weak references date from 2023, and the code is identical on
`net11`, the candidate and `main`. This is a latent bug that the CoreCLR
lane's GC timing exposed, not a candidate regression.

**Fix** (`DragAndDropDelegate.cs`, iOS/Mac Catalyst):
- `HandleDragOver` and `HandleDragLeave` call `GC.KeepAlive(session)`
after dispatching to the recognizers. The session stays alive while
handlers can synchronously call `GetPosition`, and the event args still
don't hold it strongly.
- `HandleDragOver` uses a null `sessionRef` when there is no local drag
session, matching `HandleDragLeave` and `HandleDrop`.
- `CalculatePosition` returns `null` when the session reference is
missing or its target has already been collected, instead of
dereferencing null. This covers a `GetPosition` call made after the
handler returns.

**Tests** (`DragAndDropTests.iOS.cs`, `Gesture` category):
- `DragPositionIsAvailableAfterGarbageCollectionDuringHandler(dragLeave:
false/true)`: a fake drop session returns a fresh local drag session
wrapper each time, the handler forces a full GC and then calls
`GetPosition`, and the test asserts the fake session's location.
- `DragOverPositionIsNullWithoutLocalDragSession`: with no local drag
session, `GetPosition` in `DragOver` returns `null`.

**Validation** (iOS 18.5 simulator, Release, CoreCLR, the same runtime
as the failing CI lane):

| Command | Result |
| --- | --- |
| `pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1
-Project Controls -Platform ios -TestFilter "Category=Gesture"
-DeviceUdid <iOS 18.5 sim> -SkipXcodeVersionCheck` with only the new
tests (no fix) | **Failed**: 45 passed, 3 failed. All three new cases
throw `NullReferenceException` at
`DragAndDropDelegate.CalculatePosition`, the same frame as the CI crash.
|
| Same command with the fix | **Passed**: 48 passed, 0 failed |
| `dotnet format whitespace --folder --include <changed files>
--verify-no-changes` | Passed |

The UI test itself was not rerun locally, because its crash depends on
when a GC happens.

### Issues Fixed

No existing issue; found while investigating SR2 candidate dotnet#40116 CI.
Searched for related issues and PRs and found no duplicate.
dotnet#28416/dotnet#28417 is an unrelated Mac Catalyst `DragAndDropDelegate` NRE.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@github-actions

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

Or

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

@dotnet-policy-service dotnet-policy-service Bot added the community ✨ Community Contribution label Nov 19, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

@azure-pipelines

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 19, 2026
@MauiBot

MauiBot commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

PR Test Gate

@MykhailoDav — existing-test verification; Setup did not capture a tested commit.

Result INCONCLUSIVE Platform Android


🧪 Gate analysis — click to expand

⚠ Inconclusive. Setup, build, or execution did not produce a conclusive result. This does not prove the fix is incorrect.

No interpretable test-group summary was produced. No additional test execution is inferred.

Setup did not capture a verified PR head; no commit is claimed as tested.

No immutable without-fix baseline was prepared.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Nov 19, 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 — 1 finding

Reviewed commit ca6acbc.

See inline comments for details.

}
else
{
Unsubscribe();

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] Regression Prevention and Test Coverage - The collected-handler cleanup branch has no discriminating regression test. Both AttachedTriggerDoesNotKeepPageAlive tests stop after collection, while both TriggerStillUpdatesAfterGarbageCollection tests retain their window and exercise only a live handler. Consequently, omitting this Unsubscribe call would leave every dead proxy rooted by DeviceDisplay after subsequent display changes without failing these tests; the last platform display listener would also remain registered. Add a test that collects an attached subscriber, raises a display change, and asserts that its subscription is removed, with a second live subscriber still receiving updates. The existing MockDeviceDisplay uses a plain event and does not track listener removal.

@kubaflo
kubaflo changed the base branch from net11 to candidate/11.0.1xx-sr2 November 20, 2026 19:11
@kubaflo
kubaflo merged commit bea94cc into dotnet:candidate/11.0.1xx-sr2 Nov 20, 2026
34 of 44 checks passed
@kubaflo kubaflo mentioned this pull request Nov 20, 2026
1 task
kubaflo added a commit that referenced this pull request Nov 22, 2026
…akly (#40453)

### Description of Change

`OrientationStateTrigger` and `DisplayRotationStateTrigger` subscribe to
the static `DeviceDisplay.MainDisplayInfoChanged` when attached and
unsubscribe when detached. Triggers only detach when the element's
window changes, and `Window.Destroying` doesn't clear `Page`. So when
Android recreates the Activity, the old page keeps its window, its
triggers stay subscribed, and the static event keeps the whole old page
alive (trigger → `VisualState` → setters → old page). Every recreation
leaks another page, and the dead triggers keep reacting to rotation.

The triggers now subscribe through a new `WeakDisplayInfoChangedProxy`,
built like the existing `WeakNotifyCollectionChangedProxy` in
`WeakEventProxy.cs`. Each trigger keeps its handler in a field, because
the proxy only holds it weakly. A proxy whose trigger was collected
removes itself on the next display change. Unlike `VisualElement` and
`Border`, the triggers don't unsubscribe from a finalizer: removing the
last handler stops the platform display listeners, which shouldn't
happen on the finalizer thread.

`FlyoutPage` has a similar static `MainDisplayInfoChanged` subscription;
I left it out of this PR.

### Tests

New tests in `OrientationStateTriggerTests` and
`DisplayRotationStateTriggerTests` (Controls.Core.UnitTests):
- `AttachedTriggerDoesNotKeepPageAlive` keeps a page with the trigger in
a window that is never torn down and checks that the page can be
collected. Without the fix both fail with "Page should not be alive!".
- `TriggerStillUpdatesAfterGarbageCollection` forces a GC and checks
that the trigger still reacts to a display change. It fails if the
handler isn't kept alive by the trigger.

The trigger tests go from 32/34 to 34/34. The full
Controls.Core.UnitTests run has the same single failure as clean `net11`
(`TwoWayBindingToNullableDoublePropertyWithEmptyStringBecomesNull`, a
decimal-comma locale issue on my machine).

**Before / after** (sandbox app, Android emulator API 37, Release): the
issue's XAML plus a "Collect and count" button that counts pages still
alive. The Activity is recreated three times by changing the font scale.

| Before: all 4 pages are still alive | After: only the current page is
alive |
|---|---|
|
![before](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-before.png)
|
![after](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-after.png)
|

Full clips:
[before.mp4](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-before.mp4)
·
[after.mp4](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-after.mp4).
The after clip also rotates the emulator to show the [landscape
template](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-after-landscape.png)
still switches.

Not checked: iOS, Mac Catalyst and Windows (shared code, not run there),
Debug builds and a physical device.

### Issues Fixed

Fixes #40450

---------

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Nov 23, 2026
### Description of Change

`FlyoutPage` has the same static `DeviceDisplay.MainDisplayInfoChanged`
subscription that #40453 fixed for `OrientationStateTrigger` and
`DisplayRotationStateTrigger`. It subscribes when its window is set and
unsubscribes only when the window becomes null. That causes two
problems:

- `Window.Destroying` doesn't clear `Page`, so on Android every Activity
recreation leaves the previous `FlyoutPage` rooted by the static event
when `CreateWindow` returns a new one.
- When a page moves straight from one window to another (for example a
page reused through DI), it subscribes twice. The handler then runs
twice per display change, and one subscription is left behind after the
page leaves the window.

`FlyoutPage` now subscribes through `WeakDisplayInfoChangedProxy`, the
proxy added in #40453. It keeps the delegate in a field, because the
proxy holds the handler weakly. `Subscribe` drops the previous
subscription first, which fixes the double subscription.
`OnMainDisplayInfoChanged` is unchanged.

#40453 is in `candidate/11.0.1xx-sr2` but not yet in `net11`. This PR
adds the proxy class to `WeakEventProxy.cs` with exactly the content
#40453 gave the file, so merging into a branch that already has #40453
doesn't change it.

### Tests

Two tests in `FlyoutPageUnitTests`:
- `FlyoutPageInWindowDoesNotStayAlive` puts a `FlyoutPage` in a window,
drops both, and checks the page is collected. Without the fix:
`FlyoutPage should not be alive!`
- `FlyoutPageMovedToAnotherWindowHandlesDisplayChangesOnce` moves the
page from one window to another, checks that one display change updates
`FlyoutBehavior` once, and that nothing updates after the page leaves
the window. Without the fix: `Expected: 1, Actual: 2`.

FlyoutPage tests: 55/57 → 57/57. Full Controls.Core.UnitTests: 6735
passed, 1 failed, the same failure as on clean `net11`
(`TwoWayBindingToNullableDoublePropertyWithEmptyStringBecomesNull`, a
decimal-comma locale issue on my machine).

**Before / after** (sandbox app, Android emulator API 37, Release):
`CreateWindow` returns a new `FlyoutPage`. The font scale was changed
four times to recreate the Activity, and the label shows how many
`FlyoutPage` instances are still alive after a GC.

| Before: 5 of 5 FlyoutPages still alive | After: 1 of 5 alive |
|---|---|
|
![before](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/flyoutpage-leak-before.png)
|
![after](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/flyoutpage-leak-after.png)
|

Full clips:
[before.mp4](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/flyoutpage-leak-before.mp4)
·
[after.mp4](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/flyoutpage-leak-after.mp4)

Not checked: iOS, Mac Catalyst and Windows (the change is in shared
code), and the window-to-window case in a real app (unit test only).

### Issues Fixed

Related to #40450

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 23, 2026
…akly (#40453)

### Description of Change

`OrientationStateTrigger` and `DisplayRotationStateTrigger` subscribe to
the static `DeviceDisplay.MainDisplayInfoChanged` when attached and
unsubscribe when detached. Triggers only detach when the element's
window changes, and `Window.Destroying` doesn't clear `Page`. So when
Android recreates the Activity, the old page keeps its window, its
triggers stay subscribed, and the static event keeps the whole old page
alive (trigger → `VisualState` → setters → old page). Every recreation
leaks another page, and the dead triggers keep reacting to rotation.

The triggers now subscribe through a new `WeakDisplayInfoChangedProxy`,
built like the existing `WeakNotifyCollectionChangedProxy` in
`WeakEventProxy.cs`. Each trigger keeps its handler in a field, because
the proxy only holds it weakly. A proxy whose trigger was collected
removes itself on the next display change. Unlike `VisualElement` and
`Border`, the triggers don't unsubscribe from a finalizer: removing the
last handler stops the platform display listeners, which shouldn't
happen on the finalizer thread.

`FlyoutPage` has a similar static `MainDisplayInfoChanged` subscription;
I left it out of this PR.

### Tests

New tests in `OrientationStateTriggerTests` and
`DisplayRotationStateTriggerTests` (Controls.Core.UnitTests):
- `AttachedTriggerDoesNotKeepPageAlive` keeps a page with the trigger in
a window that is never torn down and checks that the page can be
collected. Without the fix both fail with "Page should not be alive!".
- `TriggerStillUpdatesAfterGarbageCollection` forces a GC and checks
that the trigger still reacts to a display change. It fails if the
handler isn't kept alive by the trigger.

The trigger tests go from 32/34 to 34/34. The full
Controls.Core.UnitTests run has the same single failure as clean `net11`
(`TwoWayBindingToNullableDoublePropertyWithEmptyStringBecomesNull`, a
decimal-comma locale issue on my machine).

**Before / after** (sandbox app, Android emulator API 37, Release): the
issue's XAML plus a "Collect and count" button that counts pages still
alive. The Activity is recreated three times by changing the font scale.

| Before: all 4 pages are still alive | After: only the current page is
alive |
|---|---|
|
![before](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-before.png)
|
![after](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-after.png)
|

Full clips:
[before.mp4](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-before.mp4)
·
[after.mp4](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-after.mp4).
The after clip also rotates the emulator to show the [landscape
template](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-after-landscape.png)
still switches.

Not checked: iOS, Mac Catalyst and Windows (shared code, not run there),
Debug builds and a physical device.

### Issues Fixed

Fixes #40450

---------

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Nov 23, 2026
### Description of Change

`FlyoutPage` has the same static `DeviceDisplay.MainDisplayInfoChanged`
subscription that #40453 fixed for `OrientationStateTrigger` and
`DisplayRotationStateTrigger`. It subscribes when its window is set and
unsubscribes only when the window becomes null. That causes two
problems:

- `Window.Destroying` doesn't clear `Page`, so on Android every Activity
recreation leaves the previous `FlyoutPage` rooted by the static event
when `CreateWindow` returns a new one.
- When a page moves straight from one window to another (for example a
page reused through DI), it subscribes twice. The handler then runs
twice per display change, and one subscription is left behind after the
page leaves the window.

`FlyoutPage` now subscribes through `WeakDisplayInfoChangedProxy`, the
proxy added in #40453. It keeps the delegate in a field, because the
proxy holds the handler weakly. `Subscribe` drops the previous
subscription first, which fixes the double subscription.
`OnMainDisplayInfoChanged` is unchanged.

#40453 is in `candidate/11.0.1xx-sr2` but not yet in `net11`. This PR
adds the proxy class to `WeakEventProxy.cs` with exactly the content
#40453 gave the file, so merging into a branch that already has #40453
doesn't change it.

### Tests

Two tests in `FlyoutPageUnitTests`:
- `FlyoutPageInWindowDoesNotStayAlive` puts a `FlyoutPage` in a window,
drops both, and checks the page is collected. Without the fix:
`FlyoutPage should not be alive!`
- `FlyoutPageMovedToAnotherWindowHandlesDisplayChangesOnce` moves the
page from one window to another, checks that one display change updates
`FlyoutBehavior` once, and that nothing updates after the page leaves
the window. Without the fix: `Expected: 1, Actual: 2`.

FlyoutPage tests: 55/57 → 57/57. Full Controls.Core.UnitTests: 6735
passed, 1 failed, the same failure as on clean `net11`
(`TwoWayBindingToNullableDoublePropertyWithEmptyStringBecomesNull`, a
decimal-comma locale issue on my machine).

**Before / after** (sandbox app, Android emulator API 37, Release):
`CreateWindow` returns a new `FlyoutPage`. The font scale was changed
four times to recreate the Activity, and the label shows how many
`FlyoutPage` instances are still alive after a GC.

| Before: 5 of 5 FlyoutPages still alive | After: 1 of 5 alive |
|---|---|
|
![before](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/flyoutpage-leak-before.png)
|
![after](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/flyoutpage-leak-after.png)
|

Full clips:
[before.mp4](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/flyoutpage-leak-before.mp4)
·
[after.mp4](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/flyoutpage-leak-after.mp4)

Not checked: iOS, Mac Catalyst and Windows (the change is in shared
code), and the window-to-window case in a real app (unit test only).

### Issues Fixed

Related to #40450

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
…akly (dotnet#40453)

### Description of Change

`OrientationStateTrigger` and `DisplayRotationStateTrigger` subscribe to
the static `DeviceDisplay.MainDisplayInfoChanged` when attached and
unsubscribe when detached. Triggers only detach when the element's
window changes, and `Window.Destroying` doesn't clear `Page`. So when
Android recreates the Activity, the old page keeps its window, its
triggers stay subscribed, and the static event keeps the whole old page
alive (trigger → `VisualState` → setters → old page). Every recreation
leaks another page, and the dead triggers keep reacting to rotation.

The triggers now subscribe through a new `WeakDisplayInfoChangedProxy`,
built like the existing `WeakNotifyCollectionChangedProxy` in
`WeakEventProxy.cs`. Each trigger keeps its handler in a field, because
the proxy only holds it weakly. A proxy whose trigger was collected
removes itself on the next display change. Unlike `VisualElement` and
`Border`, the triggers don't unsubscribe from a finalizer: removing the
last handler stops the platform display listeners, which shouldn't
happen on the finalizer thread.

`FlyoutPage` has a similar static `MainDisplayInfoChanged` subscription;
I left it out of this PR.

### Tests

New tests in `OrientationStateTriggerTests` and
`DisplayRotationStateTriggerTests` (Controls.Core.UnitTests):
- `AttachedTriggerDoesNotKeepPageAlive` keeps a page with the trigger in
a window that is never torn down and checks that the page can be
collected. Without the fix both fail with "Page should not be alive!".
- `TriggerStillUpdatesAfterGarbageCollection` forces a GC and checks
that the trigger still reacts to a display change. It fails if the
handler isn't kept alive by the trigger.

The trigger tests go from 32/34 to 34/34. The full
Controls.Core.UnitTests run has the same single failure as clean `net11`
(`TwoWayBindingToNullableDoublePropertyWithEmptyStringBecomesNull`, a
decimal-comma locale issue on my machine).

**Before / after** (sandbox app, Android emulator API 37, Release): the
issue's XAML plus a "Collect and count" button that counts pages still
alive. The Activity is recreated three times by changing the font scale.

| Before: all 4 pages are still alive | After: only the current page is
alive |
|---|---|
|
![before](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-before.png)
|
![after](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-after.png)
|

Full clips:
[before.mp4](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-before.mp4)
·
[after.mp4](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-after.mp4).
The after clip also rotates the emulator to show the [landscape
template](https://raw.githubusercontent.com/MykhailoDav/maui/media-pr-2026-11-12/40450-after-landscape.png)
still switches.

Not checked: iOS, Mac Catalyst and Windows (shared code, not run there),
Debug builds and a physical device.

### Issues Fixed

Fixes dotnet#40450

---------

Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@MartinYanicelli

Copy link
Copy Markdown

Could this fix be considered for the next .NET MAUI 10 servicing release (release/10.0.1xx-sr14, or the next one)?

Issue #40450 was validated in triage on 10.0.130, and the code is unchanged on the .NET 10 line: on release/10.0.1xx-sr14, OrientationStateTrigger still subscribes to DeviceDisplay.MainDisplayInfoChanged strongly. On .NET 10, every Activity recreation (for example, after a font scale change) leaks the whole old page through the trigger's setters, for the life of the process. The only workaround is to replace OrientationStateTrigger with a custom trigger in every XAML file that uses it.

I simulated the cherry-pick of 2b3359f onto release/10.0.1xx-sr14 (25c4d78) with git merge-tree. The only conflict is at the end of src/Controls/src/Core/Internals/WeakEventProxy.cs, where the new WeakDisplayInfoChangedProxy class is appended, and resolving it means keeping that class. The other files apply cleanly. I didn't build or run the tests on that branch.

Could a maintainer apply backport/suggested and confirm the appropriate .NET 10 branch and release?

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — ca6acbc0 Deployed Nov 19, 2026 by MykhailoDav via conclusion #3151
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community ✨ Community Contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants