Home > Software design >  How to call a function on a WPF Windows Toast Notification button press?
How to call a function on a WPF Windows Toast Notification button press?

Time:01-29

I have been playing around with a WBF project recently and tried to implement a windows Toast notification from the Microsoft.Toolkit.Uwp.Notifications NuGet package. So I set up the notification and it works fine but how can I call a function when pressing a ToastButton? I know that I'm supposed to override the OnActivated function in my App.xaml but it keeps telling me that there is no such function to override, only one that uses EventArgs as a parameter but that one doesn't get called on the button press. This is my Toast:

new ToastContentBuilder()
                        .AddText("test")
                        .AddButton(new ToastButton()
                            .SetContent("Call function")
                            .AddArgument("action", "callFunction")
                        )
                        .AddButton(new ToastButton()
                            .SetContent("Dismiss")
                            .SetDismissActivation()
                        )
                        .Show();

So as you can see I just create a simple Toast Notification with 2 buttons. One dismisses the Notification fine but how can I call a function when I click on the other test button?

Again my App.xaml doesn't have the right OnActivated function to be overridden and the one it does have is not called on the button press. I assume this is because it is a WPF project and not a UWP project. Anyone can help me with that?

Thanks in advance

CodePudding user response:

Finally found a solution. You can subscribe your function to ToastNotificationManagerCompat like this

ToastNotificationManagerCompat.OnActivated  = toastArgs =>
{
    CheckInput(toastArgs);
};

Then whenever a toast button is pressed the CheckInput function is called. Then you can check the toastArgs.Argument parameter to see what button was pressed and inside CheckInput obviously you put your logic to handle the different button presses.

  •  Tags:  
  • Related