显示Windows 10 Toast通知

我正在用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.Runtime的引用,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b03f5f7f11d50a3a“(已翻译)

IEnumerableIReadOnlyList

错误来自这两行:

 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未定义”之类的错误等等(但是当我启动它时它仍会运行!)。

我能想到的唯一可能的解决方案是System.Runtime已经安装在我的计算机上的某个地方,并且4.0.0是我程序的错误版本。 但我无法在任何地方找到它。

PS:这是桌面应用程序,而不是Windows应用程序。

我认为这个问题和这个问题一样。你必须添加一个引用

 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\Facades\System.Runtime.dll 

PS:如果你有一个仅限Windows 10的桌面应用程序,你可能想要使用新的Toast系统,MSDN上的代码示例使用Windows 8。 它适用于W10,但没有所有新function(微软发布了官方的NuGet包)。

编辑:由于我无法发表评论,我将在此发布答案:

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

 ToastNotificationManager.CreateToastNotifier("MyApplicationId").Show(toast); 

它将在操作中心用于对您的toast进行分组的名称(通常,您将应用程序的名称设置为)。 在Windows 8.1中,需要注册您的应用程序ID(我认为这是来自MSDN的示例),但现在您只需输入应用程序的名称即可。

GetXml()仅适用于WinRT 。 在桌面中,您需要像使用GetContent()