Search code examples
c#uwpnotificationswindows-10

How can I get the content of a Windows 10 ?Notification in a UWP/C#?


I'm trying to get the text inside user notifications, and the action that occurs if you click the notification. I get the user's permission to read them (using UserNotificationListener.RequestAccessAsync()), and then I iterate over them, and add them to a ListView:

private async void getNotificationsAsync()
{
    UserNotificationListener listener = UserNotificationListener.Current;
    IReadOnlyList<UserNotification> notifs = await listener.GetNotificationsAsync(NotificationKinds.Toast);
    NotificationsList.Items.Clear();
    foreach (UserNotification notif in notifs)
    {
        //Console.WriteLine(notif.AppInfo.DisplayInfo.DisplayName);
        NotificationsList.Items.Add(notif.AppInfo.DisplayInfo.DisplayName);
    }
}

But all I can get from the UserNotification class is the initiating application's name (and the time the notification occured). I can't find any way to access the content of the notification in the UserNotification class.

Is what I'm trying possible? Am I using the right class?


Solution

  • Found it! (always happens after I ask the question 😀). For posterity's sake, here's the answer:

    NotificationBinding toastBinding = notif.Notification.Visual.GetBinding(KnownNotificationBindings.ToastGeneric);
    
    if (toastBinding != null)
    {
        // And then get the text elements from the toast binding
        IReadOnlyList<AdaptiveNotificationText> textElements = toastBinding.GetTextElements();
    
        // Treat the first text element as the title text
        string titleText = textElements.FirstOrDefault()?.Text;
    
        // We'll treat all subsequent text elements as body text,
        // joining them together via newlines.
        string bodyText = string.Join("\n", textElements.Skip(1).Select(t => t.Text));
    }