Using ToastNotificationManager in .Net5.0

Viewed 1018

I was using the following code to show a Windows 10 Toast notifications from a .NetCore 3.1 console application, where I was using objects from the following namespaces: Windows.UI.Notifications & Windows.Data.Xml.Dom, in .Net5.0 these namespaces seem to be moved to somewhere else.

 public void GenerateToast(string appid, string imageFullPath, string h1, string h2, string p1)
        {
            try
            {

                var template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04);

                var textNodes = template.GetElementsByTagName("text");

                textNodes[0].AppendChild(template.CreateTextNode(h1));
                textNodes[1].AppendChild(template.CreateTextNode(h2));
                textNodes[2].AppendChild(template.CreateTextNode(p1));

                if (File.Exists(imageFullPath))
                {
                    XmlNodeList toastImageElements = template.GetElementsByTagName("image");
                    ((XmlElement)toastImageElements[0]).SetAttribute("src", imageFullPath);
                }
                IXmlNode toastNode = template.SelectSingleNode("/toast");
                ((XmlElement)toastNode).SetAttribute("duration", "long");

                var notifier = ToastNotificationManager.CreateToastNotifier(appid);
                var notification = new ToastNotification(template);

                notifier.Show(notification);
            }
            catch (Exception)
            {
                // Ignore
            }
        }

How to get back these namespaces?

1 Answers

Solution found Here:

This option is only supported in projects that use .NET 5 (or a later release) and target Windows 10, version 1809 or a later OS release. For more background info about this scenario, see this blog post.

  1. With your project open in Visual Studio, right-click your project in Solution Explorer and choose Edit Project File. Your project file should look similar to this.

    WinExe net5.0 true
  2. Replace the value of the TargetFramework element with one of the following strings:

    net5.0-windows10.0.17763.0: Use this value if your app targets Windows 10, version 1809. net5.0-windows10.0.18362.0: Use this value if your app targets Windows 10, version 1903. net5.0-windows10.0.19041.0: Use this value if your app targets Windows 10, version 2004.

    For example, the following element is for a project that targets Windows 10, version 2004.

    net5.0-windows10.0.19041.0

  3. Save your changes and close the project file.

Related