我想向我的 wpf 应用程序添加 toast 通知。
我已按照Microsoft的从桌面 C# 应用程序发送本地 toast 通知进行操作,但我陷入了步骤 5。
我不确定如何使这段代码工作:
// Construct the visuals of the toast (using Notifications library)
ToastContent toastContent = new ToastContentBuilder()
.AddToastActivationInfo("action=viewConversation&conversationId=5", ToastActivationType.Foreground)
.AddText("Hello world!")
.GetToastContent();
// And create the toast notification
var toast = new ToastNotification(toastContent.GetXml());
// And then show it
DesktopNotificationManagerCompat.CreateToastNotifier().Show(toast);
Run Code Online (Sandbox Code Playgroud)
另外,我还在<TargetPlatformVersion>10.0</TargetPlatformVersion>.csproj 中添加了对 , 的Windows.Data引用Windows.UI。
此时,我遇到了 2 个错误:
The type 'XmlDocument' is defined in an assembly that is not referenced. You must add a reference to assembly 'Windows.Foundation.UniversalApiContract, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime'
The type 'ToastNotifier' is defined in an assembly that is not referenced. You must add a reference to assembly 'Windows.Foundation.UniversalApiContract, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime'
当我添加Windows.Foundation.UniversalApiContract作为参考时,C:\Program Files (x86)\Windows Kits\10\References\10.0.18362.0\Windows.Foundation.UniversalApiContract\8.0.0.0\Windows.Foundation.UniversalApiContract.winmd出现以下错误:
类型“ToastNotification”存在于“Windows.Foundation.UniversalApiContract,Version=8.0.0.0,Culture=neutral,PublicKeyToken=null,ContentType=WindowsRuntime”和“Windows.UI,Version=255.255.255.255,Culture=neutral,PublicKeyToken”中=null,ContentType=WindowsRuntime'
我该如何修复它?
请注意,我也尝试使用“现成的示例”,但结果相同。
新的:
有一种在 WPF 应用程序中使用 UWP Toast 通知的方法。
<TargetPlatformVersion>10.0</TargetPlatformVersion>到 .csprojpackages.config文件并选择Migrate packages.config to PackageReference...(重要步骤 - 这是我缺少的东西)Install-Package Microsoft.Toolkit.Uwp.Notifications -Version 7.0.2 检查版本现在,您应该能够使用所有 uwp 通知功能。
老的:
正如 @Andy 在评论中建议的那样,已经准备好 NuGet 包实现:github.com/Federerer/Notifications.Wpf
如果您只想要一个没有 onClick 事件等的简单通知,您可以使用此解决方案:
<TargetPlatformVersion>10.0</TargetPlatformVersion>到 .csprojWindows.UI和 的引用Windows.Datausing Windows.Data.Xml.Dom; using Windows.UI.Notifications;var message = "Sample message";
var xml = $"<?xml version=\"1.0\"?><toast><visual><binding template=\"ToastText01\"><text id=\"1\">{message}</text></binding></visual></toast>";
var toastXml = new XmlDocument();
toastXml.LoadXml(xml);
var toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier("Sample toast").Show(toast);
Run Code Online (Sandbox Code Playgroud)