[英]Showing a Windows 10 toast notification
我正在用 C# (Visual Studio 2015) 开发一个程序,我想在某种情况下向用户显示一条吐司消息。 我从 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”(已翻译)
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 未定义”之类的错误(但它在我启动时仍然运行!)。
我能想到的唯一可能的解决方案是 System.Runtime 已经安装在我的计算机上的某个地方,而 4.0.0 是我程序的错误版本。 但我在任何地方都找不到。
PS:这是一个桌面应用程序,而不是一个 Windows-Store 应用程序。
我认为这与此问题中的问题相同您必须添加对
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()
那样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.