Search code examples
c#toastmaui

How to use Toast Notifications with .Net Maui


I'm trying to show a ToastNotification in a brand new .Net Maui App.

I'm following the instructions from Microsoft about Sending a local toast notification.

I'm able to successfully create one with the code from step 2:

// Requires Microsoft.Toolkit.Uwp.Notifications NuGet package version 7.0 or greater
new ToastContentBuilder()
    .AddArgument("action", "viewConversation")
    .AddArgument("conversationId", 9813)
    .AddText("Andrew sent you a picture")
    .AddText("Check this out, The Enchantments in Washington!")
    .Show(); // Not seeing the Show() method? Make sure you have version 7.0, and if you're using .NET 6 (or later), then your TFM must be net6.0-windows10.0.17763.0 or greater

However when I add the code below (from Step 3), the Show() method throws this exception:

'System.InvalidOperationException' occurred in Microsoft.Toolkit.Uwp.Notifications.dll.

"Failed to register notification activator"

Here's the code from Step 3 that broke it. I believe it's failing at ToastNotificationManagerCompat.OnActivated:

// Listen to notification activation
ToastNotificationManagerCompat.OnActivated += toastArgs =>
{
    // Obtain the arguments from the notification
    ToastArguments args = ToastArguments.Parse(toastArgs.Argument);

    // Obtain any user input (text boxes, menu selections) from the notification
    ValueSet userInput = toastArgs.UserInput;

    Debug.WriteLine("Toast Activated!");
};

Ultimately I'm trying to add buttons to the ToastNotification and run code when they're selected.

Edit: It was failing at ToastNotificationManagerCompat.OnActivated because I didn't enable the ToastActivator in my windows project. I put a link to the solution in my answer


Solution

  • I spent the last few days researching and was able to figure it out. I created a demo project on Github to help explain/demonstrate how to get it to work. Here's the link to that: Using Toast Notifications with .Net Maui.

    The quick answer is 2 things are needed:

    1. Add the Microsoft.Toolkit.Uwp.Notifications nuget package
    2. Edit the appmanifest for the Windows Project and add support for the ToastActivator. Check this link for more info: Enabling Toast Activator.