Skip to content

Commit 965efb4

Browse files
authored
Fixed memory leak where modal pages with ToolbarItems were retained after dismissal when using x:Name on any element in the page or Clicked event on the ToolbarItem. (#839)
1 parent 7ad896d commit 965efb4

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
## [55.6.7]
2+
- Fixed memory leak where modal pages with `ToolbarItems` were retained after dismissal when using `x:Name` on any element in the page or `Clicked` event on the `ToolbarItem`.
3+
14
## [55.6.6]
25
- [Toolbar] Supports IsVisible and other visual element properties.
36

src/library/DIPS.Mobile.UI/Components/Shell/Shell.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ private static async Task TryResolvePoppedModalPages(List<ModalPageReference> mo
150150
GarbageCollection.Print($"--- 🪟 Attempting to check for leaks in every page that has ever been opened in modal: {modalPage.Name}, number of pages: {modalPage.WeakPages.Count}");
151151

152152
TryAutoDisconnectModalNavigationPageHandler(modalPage);
153+
ClearToolbarItems(modalPage);
153154

154155
// The object has already been garbage collected
155156
if (!modalPage.IsAlive)
@@ -244,6 +245,30 @@ private static void TryAutoDisconnectModalPageHandlers(List<CollectionContentTar
244245
}
245246
}
246247

248+
/// <summary>
249+
/// Clears ToolbarItems on modal pages to break the reference chain from native toolbar infrastructure
250+
/// back to the page. Without this, the native navigation bar retains toolbar item handlers which root
251+
/// the page, and any x:Name'd elements remain alive through the generated code-behind fields.
252+
/// TODO: May remove this method when https://github.com/dotnet/maui/issues/34892 is merged
253+
/// </summary>
254+
private static void ClearToolbarItems(ModalPageReference modalPage)
255+
{
256+
GarbageCollection.Print("ℹ️ Clearing ToolbarItems...");
257+
258+
foreach (var weakPage in modalPage.WeakPages)
259+
{
260+
if (weakPage.Target is Page page)
261+
{
262+
page.ToolbarItems.Clear();
263+
}
264+
}
265+
266+
if (modalPage.Target is Page modalRoot)
267+
{
268+
modalRoot.ToolbarItems.Clear();
269+
}
270+
}
271+
247272
private async static Task TryResolvePoppedPages(List<PageReference> pages,
248273
ShellNavigationSource shellNavigatedEventArgs)
249274
{

0 commit comments

Comments
 (0)