Skip to content

Commit 473c783

Browse files
Fix Windows Media Element in MultiWindow Mode on exit Crash (CommunityToolkit#2259)
* Track window count and manage snackbar notifications Added a static `NumberOfWindows` property to the `Options` class to track the number of windows. Updated `SetShouldEnableSnackbarOnWindows` to increment/decrement `NumberOfWindows` on window creation/closure. Conditional registration/unregistration of `AppNotificationManager` for snackbar notifications based on `NumberOfWindows` count. * Remove `NumberOfWindows ` * Add null check --------- Co-authored-by: Brandon Minnick <13558917+brminnick@users.noreply.github.com>
1 parent d7ea78f commit 473c783

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

src/CommunityToolkit.Maui/Options.cs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -70,19 +70,27 @@ public void SetShouldEnableSnackbarOnWindows(bool value)
7070
events.AddWindows(windows => windows
7171
.OnLaunched((_, _) =>
7272
{
73-
Microsoft.Windows.AppNotifications.AppNotificationManager.Default.NotificationInvoked += OnSnackbarNotificationInvoked;
74-
Microsoft.Windows.AppNotifications.AppNotificationManager.Default.Register();
73+
if (Application.Current is null)
74+
{
75+
throw new InvalidOperationException($"{nameof(Application)}.{nameof(Application.Current)} cannot be null when Windows are launched");
76+
}
77+
78+
else if (Application.Current.Windows.Count is 1)
79+
{
80+
Microsoft.Windows.AppNotifications.AppNotificationManager.Default.NotificationInvoked += OnSnackbarNotificationInvoked;
81+
Microsoft.Windows.AppNotifications.AppNotificationManager.Default.Register();
82+
}
7583
})
7684
.OnClosed((_, _) =>
7785
{
78-
try
86+
if (Application.Current is null)
7987
{
80-
Microsoft.Windows.AppNotifications.AppNotificationManager.Default.NotificationInvoked -= OnSnackbarNotificationInvoked;
81-
Microsoft.Windows.AppNotifications.AppNotificationManager.Default.Unregister();
88+
throw new InvalidOperationException($"{nameof(Application)}.{nameof(Application.Current)} cannot be null when Windows are closed");
8289
}
83-
catch
90+
else if (Application.Current.Windows.Count is 1)
8491
{
85-
// And Element not found exception may be thrown when unregistering the event handler after using MediaElement accross multiple Windows
92+
Microsoft.Windows.AppNotifications.AppNotificationManager.Default.NotificationInvoked -= OnSnackbarNotificationInvoked;
93+
Microsoft.Windows.AppNotifications.AppNotificationManager.Default.Unregister();
8694
}
8795
}));
8896
});

0 commit comments

Comments
 (0)