显示Windows 10 toast通知

本文关键字:通知 toast Windows 显示 | 更新日期: 2023-09-27 18:09:45

我正在c# (Visual Studio 2015)中开发一个程序,我想在特定情况下向用户显示toast消息。我从MSDN下载了这段代码,它运行良好:

// Get a toast XML template
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04);
// Fill in the text elements
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
for (int i = 0; i < stringElements.Length; i++)
{
    stringElements[i].AppendChild(toastXml.CreateTextNode("Line " + i));
}
// Specify the absolute path to an image
String imagePath = "file:///" + Path.GetFullPath("toastImageAndText.png");
XmlNodeList imageElements = toastXml.GetElementsByTagName("image");
imageElements[0].Attributes.GetNamedItem("src").NodeValue = imagePath;
// Create the toast and attach event listeners
ToastNotification toast = new ToastNotification(toastXml);
toast.Activated += ToastActivated;
toast.Dismissed += ToastDismissed;
toast.Failed += ToastFailed;
// Show the toast. Be sure to specify the AppUserModelId on your application's shortcut!
ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toast);
在测试了这段代码之后,我想把它实现到我的应用程序中。所以我对它做了一点改动,试着运行它。错误信息:

类型"IReadOnlyList<>"在未引用的程序集中定义。添加对System的引用。运行时,版本=4.0.0.0,文化=中性,PublicKeyToken=b03f5f7f11d50a3a"(翻译)

对于IEnumerable<>IReadOnlyList<>也是如此

错误来自这两行:

for (int i = 0; i < stringElements.Length; i++)
{
    stringElements[i].AppendChild(toastXml.CreateTextNode("Line " + i));

我还尝试添加引用到System.Runtime。我用NuGet (https://www.nuget.org/packages/System.Runtime/4.0.0/)下载了它。在那之后,错误消失了,但是现在我的代码中的每个字都被像"System"这样的错误弄红了。Object是未定义的"等等(但是当我启动它时它仍然运行!)

我能想到的唯一可能的解决方案就是那个系统。运行时已经安装在我的计算机上的某个地方,4.0.0是我的程序的错误版本。但是我到处都找不到。

PS:这是一个桌面应用程序,不是windows store应用程序。

显示Windows 10 toast通知

我认为这个问题和这个问题是一样的必须添加对

的引用
C:'Program Files (x86)'Reference Assemblies'Microsoft'Framework'.NETFramework'v4.5.1'Facades'System.Runtime.dll

PS:如果你有一个Windows 10的桌面应用,你可能想使用新的toast系统,MSDN上的代码示例使用Windows 8的。它可以在W10上运行,但没有所有的新功能(微软发布了一个官方的NuGet包)。

编辑:既然我不能评论,我将把答案贴在这里:

例外是因为您需要在CreateToastNotifier()

中提供applicationId
ToastNotificationManager.CreateToastNotifier("MyApplicationId").Show(toast);

这是将在操作中心用于对toast进行分组的名称(因此通常,您将使用应用程序的名称)。在Windows 8.1中,需要注册应用程序Id(我认为这是在MSDN的示例中),但现在你可以只输入应用程序的名称。

GetXml()仅适用于WinRT。在桌面,你需要像GetContent()那样做。