c# - 显示 Windows 10 toast 通知

标签 c# .net visual-studio notifications

我正在用 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);

测试此代码后,我想将其实现到我的应用程序中。所以我稍微改变了一下并尝试运行它。错误信息:

The type "IReadOnlyList<>" is defined in a not referenced assembly. Add a reference to System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" (translated)

同样适用于 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 is not defined”之类的错误(但当我启动它时它仍然运行!) .

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

PS:这是一个桌面应用程序,而不是 Windows 应用商店应用程序。

最佳答案

我认为这与 this question 中的问题相同 您必须添加对

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

PS:如果您有一个仅限 Windows 10 的桌面应用程序,您可能想要使用新的 toast 系统,MSDN 上的代码示例使用的是 Windows 8 系统。它适用于 W10,但不具备所有新功能(Microsoft 发布了官方 NuGet 软件包)。

编辑:因为我不能发表评论,所以我会在这里发布答案:

异常是因为你需要在CreateToastNotifier()中提供一个applicationId

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

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

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

关于c# - 显示 Windows 10 toast 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32214716/

相关文章:

c# - 我可以将 double 的浮点部分转换为整数(不使用字符串转换)吗?

.net - 如何检测 .NET 应用程序是否正在使用我的 COM 对象?

c# - 为什么整数零不等于长零?

c++ - 如何在 Visual Studio 2019 中使用 cmake 项目进行 "Edit and Continue"构建?

c - 如何检查我的程序使用的堆和堆栈有多少?

c# - 如果我在 catch 中添加一个只有 Debugger.Break() 的 try-catch block

c# - 通过 C# 修改对象访问属性

c# - Windows Mobile 6.5 构建时间 (VS2008)

c# - 从另一个列表中删除一个对象列表

c# - 对象和集合初始值设定项 - 分配 self ?