diff --git a/src/CommunityToolkit.Maui/Options.cs b/src/CommunityToolkit.Maui/Options.cs index 64275c397..9c70dfa89 100644 --- a/src/CommunityToolkit.Maui/Options.cs +++ b/src/CommunityToolkit.Maui/Options.cs @@ -70,19 +70,27 @@ public void SetShouldEnableSnackbarOnWindows(bool value) events.AddWindows(windows => windows .OnLaunched((_, _) => { - Microsoft.Windows.AppNotifications.AppNotificationManager.Default.NotificationInvoked += OnSnackbarNotificationInvoked; - Microsoft.Windows.AppNotifications.AppNotificationManager.Default.Register(); + if (Application.Current is null) + { + throw new InvalidOperationException($"{nameof(Application)}.{nameof(Application.Current)} cannot be null when Windows are launched"); + } + + else if (Application.Current.Windows.Count is 1) + { + Microsoft.Windows.AppNotifications.AppNotificationManager.Default.NotificationInvoked += OnSnackbarNotificationInvoked; + Microsoft.Windows.AppNotifications.AppNotificationManager.Default.Register(); + } }) .OnClosed((_, _) => { - try + if (Application.Current is null) { - Microsoft.Windows.AppNotifications.AppNotificationManager.Default.NotificationInvoked -= OnSnackbarNotificationInvoked; - Microsoft.Windows.AppNotifications.AppNotificationManager.Default.Unregister(); + throw new InvalidOperationException($"{nameof(Application)}.{nameof(Application.Current)} cannot be null when Windows are closed"); } - catch + else if (Application.Current.Windows.Count is 1) { - // And Element not found exception may be thrown when unregistering the event handler after using MediaElement accross multiple Windows + Microsoft.Windows.AppNotifications.AppNotificationManager.Default.NotificationInvoked -= OnSnackbarNotificationInvoked; + Microsoft.Windows.AppNotifications.AppNotificationManager.Default.Unregister(); } })); });