Skip to content

Fix ShellItem.MenuItem memory leak caused by implicit wrapper - #38804

Merged
kubaflo merged 6 commits into
dotnet:inflight/currentfrom
devanathan-vaithiyanathan:fix-38579
Sep 30, 2026
Merged

kubaflo merged 6 commits into
dotnet:inflight/currentfrom
devanathan-vaithiyanathan:fix-38579

Conversation

@devanathan-vaithiyanathan

@devanathan-vaithiyanathan devanathan-vaithiyanathan commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Issue Details

MenuItem is implicitly wrapped in an internal MenuShellItem when added to Shell. The wrapper assigns itself as the MenuItem.Parent and subscribes to MenuItem.PropertyChanged.

When the wrapper is removed from Shell, these references were not released. A long-lived MenuItem could therefore retain the wrapper, its BindingContext, and the associated object graph, causing a managed memory leak on all platforms.

Description of Change

Added connection lifecycle management to MenuShellItem:

  • Connects when the wrapper receives a parent.
  • Subscribes to MenuItem.PropertyChanged.
  • Assigns the wrapper as the MenuItem.Parent.
  • Disconnects when the wrapper is removed from its parent.
  • Unsubscribes from PropertyChanged.
  • Clears MenuItem.Parent when it still references the wrapper.
  • Uses _isConnected to prevent duplicate subscriptions and cleanup.

Issues Fixed

Fixes #38579

Tested the behavior in the following platforms.

  • Android
  • Windows
  • iOS
  • Mac
Before After
Android
Android

@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 -- 38804

Or

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

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

@kubaflo

This comment has been minimized.

@kubaflo

kubaflo commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

/azp run

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

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15429719 is running for android.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 1 findings

See inline comments for details.

MauiBot

This comment was marked as outdated.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-fix-win AI found a better alternative fix than the PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Sep 23, 2026
@kubaflo

This comment has been minimized.

@github-actions

This comment has been minimized.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

AI Review Summary

@devanathan-vaithiyanathan — new AI review results are available based on commit 6aafc7c.

Gate Passed Confidence Medium Platform Android


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

Gate Result: ✅ PASSED

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

Test Without Fix (expect FAIL) With Fix (expect PASS)
🧪 ShellTests ShellTests ✅ FAIL — 116s ✅ PASS — 91s
🔴 Without fix — 🧪 ShellTests: FAIL ✅ · 116s

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

     at Microsoft.Maui.Controls.Core.UnitTests.ShellTests.LongLivedMenuItemDoesNotRetainImplicitShellItem() in /_/src/Controls/tests/Core.UnitTests/ShellTests.cs:line 791
     at Microsoft.Maui.Controls.Core.UnitTests.ShellTests.LongLivedMenuItemDoesNotRetainRemovedShellItem() in /_/src/Controls/tests/Core.UnitTests/ShellTests.cs:line 812
     at Microsoft.Maui.Controls.Core.UnitTests.ShellTests.MenuItemPropertyChangedIsObservedWhileConnected() in /_/src/Controls/tests/Core.UnitTests/ShellTests.cs:line 854
   at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
🟢 With fix — 🧪 ShellTests: PASS ✅ · 91s

(no coded error found; showing last 1200 chars)

hellPageDisconnectsHandlers [71 ms]
  Passed VisualPropagationPageLevel [< 1 ms]
  Passed ClearingShellSectionAndReAddingSetsCurrentItem [1 ms]
  Passed ShellFlyoutChangeableOnShellWithFlyoutItem [1 ms]
  Passed FlyoutNavigateToImplicitContentPage [2 ms]
  Passed SameRouteInDifferentParentsIsAllowed [< 1 ms]
  Passed NavigationProxyWireUpTest [< 1 ms]
  Passed MenuItemPropertyChangedIsObservedWhileConnected [< 1 ms]
  Passed HidingShellSectionSetsNewCurrentItem [< 1 ms]
  Passed HotReloadStaysOnActiveItem [2 ms]
  Passed OnBackbuttonPressedPageReturnsFalse [2 ms]
  Passed ShellFlyoutChangeableOnShellWithTabBar [1 ms]
  Passed SimpleGoTo [1 ms]
  Passed ShellToolbarNotVisibleWithBasicContentPage [< 1 ms]
  Passed MenuItemBindingContext [< 1 ms]
  Passed CantNavigateToNotVisibleShellItem [2 ms]
  Passed SettingCurrentItemOnShellViaContentPage [1 ms]
  Passed ShellToolbarTitleIgnoresModalTitle [1 ms]
  Passed PopToRootShellPagesDisconnectHandlers [5 ms]
  Passed ShellSectionChangedFires [2 ms]
[xUnit.net 00:00:02.26]   Finished:    Microsoft.Maui.Controls.Core.UnitTests
  Passed ShellToolbarTitle [< 1 ms]
Test Run Successful.
Total tests: 91
     Passed: 91
 Total time: 2.7600 Seconds
📁 Fix files reverted (1 files)
  • src/Controls/src/Core/Shell/MenuShellItem.cs

📋 Pre-Flight — Context & Validation

Pre-Flight — PR #38804

Context

  • PR: #38804 — Fix ShellItem.MenuItem memory leak caused by implicit wrapper
  • Issue: #38579 — [leak-scan] ShellItem.MenuItem — implicit wrapper remains rooted by source item
  • Base: main
  • Platform requested for STEP 5a: Android
  • Gate: Passed before this step; do not rerun or modify gate/content.md.

Problem

The public implicit conversion from MenuItem to ShellItem creates an internal
MenuShellItem. On the broken baseline, the wrapper sets itself as
MenuItem.Parent and subscribes directly to MenuItem.PropertyChanged. A
long-lived MenuItem therefore retains the wrapper through both relationships,
and the wrapper can retain its binding context and associated object graph.

Retention path:

long-lived MenuItem -> Parent / PropertyChanged delegate -> MenuShellItem -> BindingContext

The bug is cross-platform managed Shell behavior. Android is the requested test
platform, but the detected primary validation is a platform-independent Controls
unit-test selection.

Submitted Fix

The PR changes:

  • src/Controls/src/Core/Shell/MenuShellItem.cs
  • src/Controls/tests/Core.UnitTests/ShellTests.cs

The submitted implementation moves parenting and property observation into an
OnParentSet connect/disconnect lifecycle, uses
WeakNotifyPropertyChangedProxy, clears MenuItem.Parent when disconnecting if
the wrapper still owns it, limits inherited binding-context propagation to the
connected state, and resynchronizes template/visibility on reconnect.

The tests added by the PR verify:

  1. An unattached implicit wrapper is collectible while the source MenuItem
    remains alive.
  2. A wrapper removed from Shell.Items is collectible and clears
    MenuItem.Parent.
  3. MenuItem property changes are observed while connected and ignored after
    removal.

Alternative-Fix Constraints

  • Candidate implementations may edit only paths listed in
    .github/.baseline-state.json under RevertedFiles after
    EstablishBrokenBaseline.ps1 runs.
  • The submitted parent-aware lifecycle plus weak proxy is the existing approach
    and must not simply be repeated.
  • Preserve connected property synchronization, binding-context inheritance,
    flyout visibility synchronization, remove/re-add behavior, and protection
    against clearing a different current parent.
  • No public API change is expected.
  • Each candidate receives one implementation/test pass and at most one focused
    correction/retest.
  • Restore only with
    pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore.

Required Test Command

Run only this detected primary selection, which includes the mandatory
regressions:

dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~LongLivedMenuItemDoesNotRetainImplicitShellItem|FullyQualifiedName~LongLivedMenuItemDoesNotRetainRemovedShellItem|FullyQualifiedName~MenuItemPropertyChangedIsObservedWhileConnected|FullyQualifiedName~MenuItemBindingContext|FullyQualifiedName~FlyoutMenuItemIsVisibleSynchronized"

Do not run the Gate verification or any broader/full suite.

Pre-Flight Outcome

The diff and issue were inspected directly. No code was modified, and no
separate expert-review agent was launched. GitHub CLI authentication was
unavailable, so public GitHub API data and the local squashed PR branch were
used.


🔬 Code Review — Deep Analysis

Expert PR Evaluation

Verdict: LGTM
Confidence: Medium

Independent Assessment

The submitted fix makes the implicit MenuShellItem wrapper connect only while it belongs to a Shell parent. Connection assigns the wrapper as MenuItem.Parent, synchronizes template and visibility state, and observes property changes through WeakNotifyPropertyChangedProxy; disconnection removes the observation and clears the parent only when the wrapper still owns it. This breaks the detached-wrapper retention path while preserving connected inheritance and synchronization behavior.

Findings

No blocking errors, warnings, or inline findings were found. The required inline-findings.json contains an empty JSON array.

Blast Radius and Failure-Mode Probing

  • Connection/disconnection: _isConnected makes the lifecycle symmetric and prevents duplicate observation. Removing and re-adding the wrapper disconnects and then resynchronizes state on reconnect.
  • Reparenting: OnParentSet follows current parent nullability, so detach/reattach cycles transition cleanly.
  • Duplicate subscriptions: The connection latch and proxy subscription lifecycle prevent handlers from accumulating.
  • Parent ownership: Disconnection clears MenuItem.Parent only when it still references this wrapper, avoiding damage to a newer owner.
  • Binding context: Propagation to the source MenuItem is limited to the connected state, so a detached wrapper no longer extends the retained object graph.
  • Startup/static impact: The change adds no startup path or shared/static state; it is localized to implicit Shell menu wrappers.

Validation Evidence

The trusted Gate passed: the regression tests fail without the submitted fix and pass with it. Gate verification was not rerun.

Consolidated Refinement Recommendation

Add one focused regression test that reassigns MenuItem.Parent before the wrapper disconnects and verifies that disconnection preserves the newer parent. This directly protects the ownership guard already present in the submitted implementation; no production-code change is needed.

External Output Contract

Not applicable.


🛠️ Try-Fix — Analysis & Comparison

Aggregate Try-Fix Results — PR #38804

Candidate 1 — gpt-5.3-codex

Approach: Remove both source-to-wrapper retention edges and project
connected state through bindings. The candidate never assigns
MenuItem.Parent and never subscribes to MenuItem.PropertyChanged; attached
template and visibility values are bound only while connected and frozen on
disconnect.

Difference from the PR: The submitted fix creates relationships while the
wrapper is parented and explicitly detaches them. Candidate 1 instead attempts
to avoid creating either reverse relationship at all.

Result: Fail. After the initial implementation/test pass and the single
allowed focused correction/retest, compilation still failed with CS0246 for
unresolved Type converter parameters and CS0535 for incomplete
IValueConverter implementations. No selected test ran.

Test command: The required five-test Controls.Core.UnitTests filter only.
No Gate verification or broader suite was run.

Self-review: 1 moderate finding.

Diff: See
CustomAgentLogsTmp/PRState/38804/PRAgent/try-fix-1/content.md and
CustomAgentLogsTmp/PRState/38804/PRAgent/try-fix/attempt-1/fix.diff.

Artifacts: CustomAgentLogsTmp/PRState/38804/PRAgent/try-fix/attempt-1

Restoration: Confirmed Restored True.

Candidate 2 — gpt-5.6-sol

Approach: Store one observer relay per source MenuItem in a
ConditionalWeakTable. The relay is strongly owned by the source but retains
generated wrappers only through weak references and forwards notifications only
to attached wrappers.

Difference from prior approaches: Candidate 2 neither creates and detaches
per-wrapper parent/proxy relationships like the PR nor uses Candidate 1's
converter-backed connected-state bindings. Its source-owned relay remains
subscribed for the source lifetime, while weak targets break the retention path.

Result: Pass. The required five-test selection passed on the first run:

Failed: 0, Passed: 5, Skipped: 0, Total: 5, Duration: 293 ms

No post-test correction/retest, Gate verification, or broader suite was run.

Self-review: 1 moderate finding. Omitting MenuItem.Parent may regress
ancestor-resource and DynamicResource propagation; this scenario is outside
the selected regression set. A pre-test major binding-context retention issue
was corrected before the sole test run.

Diff: See
CustomAgentLogsTmp/PRState/38804/PRAgent/try-fix-2/content.md and
CustomAgentLogsTmp/PRState/38804/PRAgent/try-fix/attempt-2/fix.diff.

Artifacts: CustomAgentLogsTmp/PRState/38804/PRAgent/try-fix/attempt-2

Restoration: Confirmed Restored True.

Aggregate Outcome

Candidate Mechanism Result Qualification
1 — gpt-5.3-codex Binding-only connected projection Fail Did not compile after its one allowed correction
2 — gpt-5.6-sol Source-owned observer hub with weak wrapper targets Pass Five selected tests passed; one moderate resource-inheritance risk remains

Exactly two candidates were attempted sequentially. Neither candidate was left
applied to the worktree.


📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the current metadata is accurate, but the title does not follow the component-prefixed format and the description omits the weak proxy, reconnect synchronization, and submitted regression-test details.

Recommended title

[Core] Shell: Fix MenuItem leak caused by implicit MenuShellItem wrapper

Recommended description

### Issue Details

`MenuItem` is implicitly wrapped in an internal `MenuShellItem` when added to `Shell`. The wrapper assigned itself as `MenuItem.Parent` and subscribed to `MenuItem.PropertyChanged`.

When the wrapper was removed from `Shell`, those relationships were not released. A long-lived `MenuItem` could therefore retain the wrapper, its `BindingContext`, and the associated object graph, causing a managed memory leak on all platforms.

### Description of Change

Added parent-driven connection lifecycle management to `MenuShellItem` in `src/Controls/src/Core/Shell/MenuShellItem.cs`:

* Connects when the wrapper receives a parent and disconnects when it is removed from its parent.
* Assigns the wrapper as `MenuItem.Parent` only while connected.
* Observes `MenuItem.PropertyChanged` through `WeakNotifyPropertyChangedProxy` while connected and unsubscribes when disconnected.
* Clears `MenuItem.Parent` on disconnect only when it still references that wrapper, so a newer owner is not overwritten.
* Propagates inherited `BindingContext` only while connected.
* Resynchronizes `MenuItemTemplate` and flyout visibility when reconnecting.
* Uses `_isConnected` to prevent duplicate subscriptions and cleanup.

Added regression coverage in `src/Controls/tests/Core.UnitTests/ShellTests.cs` for:

* Collecting an unattached implicit wrapper while its source `MenuItem` remains alive.
* Collecting a removed wrapper and clearing its `MenuItem.Parent` relationship.
* Observing `MenuItem` template changes while connected and stopping observation after removal.

### Issues Fixed

Fixes #38579

**Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac

| Before  | After  |
|---------|--------|
| **Android**<br> <img src="https://github.com/user-attachments/assets/6694ded9-fab6-4b95-a7ee-8b89fed9a048" width="300" height="600"> | **Android**<br> <img src="https://github.com/user-attachments/assets/9081afe5-7c29-4b9a-9a9c-ad44086cac2b" width="300" height="600"> |

🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winner: pr-plus-reviewer

pr-plus-reviewer keeps the submitted production fix intact and adds the expert reviewer's focused regression test for the existing parent-ownership guard. All six targeted tests passed in the mandated sandbox, including the new scenario where MenuItem.Parent is reassigned before the wrapper disconnects. This is the smallest improvement over an otherwise sound PR and gives the guard direct regression protection.

Expert Review of the Submitted Fix

The single expert review returned LGTM with medium confidence and no inline findings. The submitted parent-driven connection lifecycle is symmetric, prevents duplicate observation, resynchronizes state after reconnect, limits binding-context propagation to connected wrappers, and clears MenuItem.Parent only when the wrapper still owns it. The trusted Gate passed: the relevant tests failed without the fix and passed with it.

Candidate Comparison

Rank Candidate Validation Assessment
1 pr-plus-reviewer Pass: 6/6 targeted tests Same sound production fix as the PR, plus direct coverage that disconnect preserves a newer MenuItem.Parent. No production-code risk added.
2 pr Pass: trusted Gate, 91/91 selected ShellTests with the fix Expert-reviewed as sound with no blocking findings. Ranked below the winner only because the ownership guard remains untested in the submitted HEAD.
3 try-fix-2 Pass: 5/5 targeted tests The ConditionalWeakTable observer relay breaks the tested retention path, but it omits MenuItem.Parent entirely and may regress ancestor-resource or DynamicResource propagation. It also adds shared relay machinery and source-lifetime subscriptions without coverage for that compatibility risk.
4 try-fix-1 Fail: compilation errors; 0 tests ran The binding-only projection remained non-buildable after its allowed correction (CS0246 and CS0535) and therefore ranks below every passing candidate.

Why the Winner Is Preferred

The raw PR already uses the least risky production approach: it preserves the established parent relationship while making that relationship and property observation follow the wrapper's actual attachment lifecycle. try-fix-2 passes the narrow regression set but changes inheritance semantics, and try-fix-1 cannot compile. The reviewer refinement improves only test coverage, so it preserves the PR's behavior while making the ownership edge case measurable.

Required Change

Apply the pr-plus-reviewer/reviewer.patch test addition to the submitted PR. No production-code revision is recommended.


📱 UI Tests — Shell

Detected UI test categories: Shell

✅ Deep UI tests — 336 passed, 0 failed, 13 skipped across 1 category on platform-pool agent (replaces in-process counts above).

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
Shell 336/349 (13 skipped) ✓ —
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)

🧭 Next Steps — reviewer changes required

The reviewer-enhanced candidate identified changes that are not yet in the submitted PR.

Why: The submitted production fix is sound, passes the trusted Gate, and has no expert-review findings. The pr-plus-reviewer candidate wins because it preserves that implementation while adding a passing focused regression test for the parent-ownership guard.

Address the actionable findings in this review before merging.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR and removed s/agent-approved AI agent recommends approval - PR fix is correct and optimal s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-review-in-progress AI review is currently running for this PR labels Sep 28, 2026
@kubaflo

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

The /review tests workflow failed before publishing a report. View the workflow run.

This is an automation failure, not a verdict on the PR tests. Maintainers can retry /review tests after the workflow failure is resolved.

@kubaflo
kubaflo changed the base branch from main to inflight/current September 30, 2026 10:45
@kubaflo
kubaflo merged commit 944fa59 into dotnet:inflight/current Sep 30, 2026
184 of 198 checks passed
@github-actions github-actions Bot added this to the .NET 10 SR12 milestone Sep 30, 2026

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.

Copilot review overview

🔵 Needs a closer look

Shell replacement may leave wrapper references connected, retaining the old object graph.

Review effort: Lite
Findings: None

Resolved since last review (1)

kubaflo pushed a commit that referenced this pull request Oct 3, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
### Issue Details
MenuItem is implicitly wrapped in an internal MenuShellItem when added
to Shell. The wrapper assigns itself as the MenuItem.Parent and
subscribes to MenuItem.PropertyChanged.
 
When the wrapper is removed from Shell, these references were not
released. A long-lived MenuItem could therefore retain the wrapper, its
BindingContext, and the associated object graph, causing a managed
memory leak on all platforms.

### Description of Change

<!-- Enter description of the fix in this section -->
Added connection lifecycle management to MenuShellItem:
* Connects when the wrapper receives a parent.
* Subscribes to MenuItem.PropertyChanged.
* Assigns the wrapper as the MenuItem.Parent.
* Disconnects when the wrapper is removed from its parent.
* Unsubscribes from PropertyChanged.
* Clears MenuItem.Parent when it still references the wrapper.
* Uses _isConnected to prevent duplicate subscriptions and cleanup.

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

Fixes #38579 

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

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac


| Before  | After  |
|---------|--------|
| **Android**<br> <img
src="https://github.com/user-attachments/assets/6694ded9-fab6-4b95-a7ee-8b89fed9a048"
width="300" height="600"> | **Android**<br> <img
src="https://github.com/user-attachments/assets/9081afe5-7c29-4b9a-9a9c-ad44086cac2b"
width="300" height="600"> |
kubaflo pushed a commit that referenced this pull request Oct 6, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
### Issue Details
MenuItem is implicitly wrapped in an internal MenuShellItem when added
to Shell. The wrapper assigns itself as the MenuItem.Parent and
subscribes to MenuItem.PropertyChanged.
 
When the wrapper is removed from Shell, these references were not
released. A long-lived MenuItem could therefore retain the wrapper, its
BindingContext, and the associated object graph, causing a managed
memory leak on all platforms.

### Description of Change

<!-- Enter description of the fix in this section -->
Added connection lifecycle management to MenuShellItem:
* Connects when the wrapper receives a parent.
* Subscribes to MenuItem.PropertyChanged.
* Assigns the wrapper as the MenuItem.Parent.
* Disconnects when the wrapper is removed from its parent.
* Unsubscribes from PropertyChanged.
* Clears MenuItem.Parent when it still references the wrapper.
* Uses _isConnected to prevent duplicate subscriptions and cleanup.

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

Fixes #38579 

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

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac


| Before  | After  |
|---------|--------|
| **Android**<br> <img
src="https://github.com/user-attachments/assets/6694ded9-fab6-4b95-a7ee-8b89fed9a048"
width="300" height="600"> | **Android**<br> <img
src="https://github.com/user-attachments/assets/9081afe5-7c29-4b9a-9a9c-ad44086cac2b"
width="300" height="600"> |
kubaflo pushed a commit that referenced this pull request Oct 13, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
### Issue Details
MenuItem is implicitly wrapped in an internal MenuShellItem when added
to Shell. The wrapper assigns itself as the MenuItem.Parent and
subscribes to MenuItem.PropertyChanged.
 
When the wrapper is removed from Shell, these references were not
released. A long-lived MenuItem could therefore retain the wrapper, its
BindingContext, and the associated object graph, causing a managed
memory leak on all platforms.

### Description of Change

<!-- Enter description of the fix in this section -->
Added connection lifecycle management to MenuShellItem:
* Connects when the wrapper receives a parent.
* Subscribes to MenuItem.PropertyChanged.
* Assigns the wrapper as the MenuItem.Parent.
* Disconnects when the wrapper is removed from its parent.
* Unsubscribes from PropertyChanged.
* Clears MenuItem.Parent when it still references the wrapper.
* Uses _isConnected to prevent duplicate subscriptions and cleanup.

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

Fixes #38579 

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

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac


| Before  | After  |
|---------|--------|
| **Android**<br> <img
src="https://github.com/user-attachments/assets/6694ded9-fab6-4b95-a7ee-8b89fed9a048"
width="300" height="600"> | **Android**<br> <img
src="https://github.com/user-attachments/assets/9081afe5-7c29-4b9a-9a9c-ad44086cac2b"
width="300" height="600"> |
kubaflo pushed a commit that referenced this pull request Oct 14, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
### Issue Details
MenuItem is implicitly wrapped in an internal MenuShellItem when added
to Shell. The wrapper assigns itself as the MenuItem.Parent and
subscribes to MenuItem.PropertyChanged.
 
When the wrapper is removed from Shell, these references were not
released. A long-lived MenuItem could therefore retain the wrapper, its
BindingContext, and the associated object graph, causing a managed
memory leak on all platforms.

### Description of Change

<!-- Enter description of the fix in this section -->
Added connection lifecycle management to MenuShellItem:
* Connects when the wrapper receives a parent.
* Subscribes to MenuItem.PropertyChanged.
* Assigns the wrapper as the MenuItem.Parent.
* Disconnects when the wrapper is removed from its parent.
* Unsubscribes from PropertyChanged.
* Clears MenuItem.Parent when it still references the wrapper.
* Uses _isConnected to prevent duplicate subscriptions and cleanup.

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

Fixes #38579 

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

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac


| Before  | After  |
|---------|--------|
| **Android**<br> <img
src="https://github.com/user-attachments/assets/6694ded9-fab6-4b95-a7ee-8b89fed9a048"
width="300" height="600"> | **Android**<br> <img
src="https://github.com/user-attachments/assets/9081afe5-7c29-4b9a-9a9c-ad44086cac2b"
width="300" height="600"> |
kubaflo pushed a commit that referenced this pull request Oct 18, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
### Issue Details
MenuItem is implicitly wrapped in an internal MenuShellItem when added
to Shell. The wrapper assigns itself as the MenuItem.Parent and
subscribes to MenuItem.PropertyChanged.
 
When the wrapper is removed from Shell, these references were not
released. A long-lived MenuItem could therefore retain the wrapper, its
BindingContext, and the associated object graph, causing a managed
memory leak on all platforms.

### Description of Change

<!-- Enter description of the fix in this section -->
Added connection lifecycle management to MenuShellItem:
* Connects when the wrapper receives a parent.
* Subscribes to MenuItem.PropertyChanged.
* Assigns the wrapper as the MenuItem.Parent.
* Disconnects when the wrapper is removed from its parent.
* Unsubscribes from PropertyChanged.
* Clears MenuItem.Parent when it still references the wrapper.
* Uses _isConnected to prevent duplicate subscriptions and cleanup.

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

Fixes #38579 

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

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac


| Before  | After  |
|---------|--------|
| **Android**<br> <img
src="https://github.com/user-attachments/assets/6694ded9-fab6-4b95-a7ee-8b89fed9a048"
width="300" height="600"> | **Android**<br> <img
src="https://github.com/user-attachments/assets/9081afe5-7c29-4b9a-9a9c-ad44086cac2b"
width="300" height="600"> |
kubaflo pushed a commit that referenced this pull request Oct 21, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
### Issue Details
MenuItem is implicitly wrapped in an internal MenuShellItem when added
to Shell. The wrapper assigns itself as the MenuItem.Parent and
subscribes to MenuItem.PropertyChanged.
 
When the wrapper is removed from Shell, these references were not
released. A long-lived MenuItem could therefore retain the wrapper, its
BindingContext, and the associated object graph, causing a managed
memory leak on all platforms.

### Description of Change

<!-- Enter description of the fix in this section -->
Added connection lifecycle management to MenuShellItem:
* Connects when the wrapper receives a parent.
* Subscribes to MenuItem.PropertyChanged.
* Assigns the wrapper as the MenuItem.Parent.
* Disconnects when the wrapper is removed from its parent.
* Unsubscribes from PropertyChanged.
* Clears MenuItem.Parent when it still references the wrapper.
* Uses _isConnected to prevent duplicate subscriptions and cleanup.

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

Fixes #38579 

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

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac


| Before  | After  |
|---------|--------|
| **Android**<br> <img
src="https://github.com/user-attachments/assets/6694ded9-fab6-4b95-a7ee-8b89fed9a048"
width="300" height="600"> | **Android**<br> <img
src="https://github.com/user-attachments/assets/9081afe5-7c29-4b9a-9a9c-ad44086cac2b"
width="300" height="600"> |
kubaflo pushed a commit that referenced this pull request Oct 25, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
### Issue Details
MenuItem is implicitly wrapped in an internal MenuShellItem when added
to Shell. The wrapper assigns itself as the MenuItem.Parent and
subscribes to MenuItem.PropertyChanged.
 
When the wrapper is removed from Shell, these references were not
released. A long-lived MenuItem could therefore retain the wrapper, its
BindingContext, and the associated object graph, causing a managed
memory leak on all platforms.

### Description of Change

<!-- Enter description of the fix in this section -->
Added connection lifecycle management to MenuShellItem:
* Connects when the wrapper receives a parent.
* Subscribes to MenuItem.PropertyChanged.
* Assigns the wrapper as the MenuItem.Parent.
* Disconnects when the wrapper is removed from its parent.
* Unsubscribes from PropertyChanged.
* Clears MenuItem.Parent when it still references the wrapper.
* Uses _isConnected to prevent duplicate subscriptions and cleanup.

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

Fixes #38579 

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

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac


| Before  | After  |
|---------|--------|
| **Android**<br> <img
src="https://github.com/user-attachments/assets/6694ded9-fab6-4b95-a7ee-8b89fed9a048"
width="300" height="600"> | **Android**<br> <img
src="https://github.com/user-attachments/assets/9081afe5-7c29-4b9a-9a9c-ad44086cac2b"
width="300" height="600"> |
kubaflo pushed a commit that referenced this pull request Oct 26, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
### Issue Details
MenuItem is implicitly wrapped in an internal MenuShellItem when added
to Shell. The wrapper assigns itself as the MenuItem.Parent and
subscribes to MenuItem.PropertyChanged.
 
When the wrapper is removed from Shell, these references were not
released. A long-lived MenuItem could therefore retain the wrapper, its
BindingContext, and the associated object graph, causing a managed
memory leak on all platforms.

### Description of Change

<!-- Enter description of the fix in this section -->
Added connection lifecycle management to MenuShellItem:
* Connects when the wrapper receives a parent.
* Subscribes to MenuItem.PropertyChanged.
* Assigns the wrapper as the MenuItem.Parent.
* Disconnects when the wrapper is removed from its parent.
* Unsubscribes from PropertyChanged.
* Clears MenuItem.Parent when it still references the wrapper.
* Uses _isConnected to prevent duplicate subscriptions and cleanup.

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

Fixes #38579 

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

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac


| Before  | After  |
|---------|--------|
| **Android**<br> <img
src="https://github.com/user-attachments/assets/6694ded9-fab6-4b95-a7ee-8b89fed9a048"
width="300" height="600"> | **Android**<br> <img
src="https://github.com/user-attachments/assets/9081afe5-7c29-4b9a-9a9c-ad44086cac2b"
width="300" height="600"> |
github-actions Bot pushed a commit that referenced this pull request Oct 28, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!
### Issue Details
MenuItem is implicitly wrapped in an internal MenuShellItem when added
to Shell. The wrapper assigns itself as the MenuItem.Parent and
subscribes to MenuItem.PropertyChanged.
 
When the wrapper is removed from Shell, these references were not
released. A long-lived MenuItem could therefore retain the wrapper, its
BindingContext, and the associated object graph, causing a managed
memory leak on all platforms.

### Description of Change

<!-- Enter description of the fix in this section -->
Added connection lifecycle management to MenuShellItem:
* Connects when the wrapper receives a parent.
* Subscribes to MenuItem.PropertyChanged.
* Assigns the wrapper as the MenuItem.Parent.
* Disconnects when the wrapper is removed from its parent.
* Unsubscribes from PropertyChanged.
* Clears MenuItem.Parent when it still references the wrapper.
* Uses _isConnected to prevent duplicate subscriptions and cleanup.

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

Fixes #38579 

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

 **Tested the behavior in the following platforms.**
- [x] Android
- [x] Windows
- [x] iOS
- [x] Mac


| Before  | After  |
|---------|--------|
| **Android**<br> <img
src="https://github.com/user-attachments/assets/6694ded9-fab6-4b95-a7ee-8b89fed9a048"
width="300" height="600"> | **Android**<br> <img
src="https://github.com/user-attachments/assets/9081afe5-7c29-4b9a-9a9c-ad44086cac2b"
width="300" height="600"> |
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 31, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

community ✨ Community Contribution partner/syncfusion Issues / PR's with Syncfusion collaboration s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[leak-scan] ShellItem.MenuItem — implicit wrapper remains rooted by source item

4 participants