Search code examples
push-notificationuwpwindows-10toastwns

how to dismiss a toast in uwp on button click


My uwp app receives toast notification from php server. It have two action buttons "View" and "Dismiss". These buttons works properly when the app is currently on activated state. (View button click redirect to a new page and Dismiss button click will not do nothing.). But when the app is in closed state - when user clicks on Dismiss button of notification, launch icon of app is coming. How can I stop this? I want to dismiss the notification when user clicks on Dismiss button.

 $toastMessage= '<toast launch="app-defined-string">'.
 '<visual>'.
'<binding template="ToastGeneric">'.
  '<text>'.$title.'</text>'.
  '<text>'.$subtitle.'</text>'.
  '</binding>'.
 '</visual>'.
'<audio src="ms-winsoundevent:Notification.SMS"  />'.
'<actions>'.
'<action activationType="foreground" content="View"  arguments="viewdetails"/>'.
 '<action content="Dismiss" arguments="later"/>'.
 '</actions>'.  
  '</toast>';

protected override void OnActivated(IActivatedEventArgs args)
    {
       if (args.Kind == ActivationKind.ToastNotification)
        {
            var toastArgs = args as ToastNotificationActivatedEventArgs;
            var arguments = toastArgs.Argument;

            if (arguments == "viewdetails" || arguments== "app-defined-string")
            {
                Frame rootFrame = Window.Current.Content as Frame;
                if (rootFrame == null)
                {
                    rootFrame = new Frame();
                    Window.Current.Content = rootFrame;
                }
                rootFrame.Navigate(typeof(PushNotificationPage));
                Window.Current.Activate();
            }
        }
    }

Solution

  • The toast content docs describe how to add a dismiss button in the snooze/dismiss section: https://learn.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/adaptive-interactive-toasts#snoozedismiss

    <action activationType="system" arguments="dismiss" content=""/>

    Basically, set the activationType to system and the arguments to dismiss. Set content to an empty string and the localized text for dismiss will be automatically used.