如何在WPF应用程序中集成toast通知



我想在我的wpf应用程序中添加toast通知。

我已经遵循了微软桌面C#应用程序的"发送本地吐司通知",但我被困在了第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);

此外,我还将<TargetPlatformVersion>10.0</TargetPlatformVersion>添加到.csproj中,引用了Windows.DataWindows.UI

在这一点上,我得到了两个错误:

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'

当我从C:Program Files (x86)Windows Kits10References10.0.18362.0Windows.Foundation.UniversalApiContract8.0.0.0Windows.Foundation.UniversalApiContract.winmd添加Windows.Foundation.UniversalApiContract作为参考时,我得到以下错误:

类型"ToastNotification"同时存在于"Windows.Foundation.UniversalApiContact,Version=8.0.0.0,Culture=neutral,PublicKeyToken=null,ContentType=WindowsRuntime"one_answers"Windows.UI,Version=255.255.255.255,Culture=neutral、PublicKeyToken=null,ContentType=WindowsRuntime"中

如何修复它?

请注意,我也尝试过使用"现成的示例",但结果相同。

新增:

有一种方法可以在WPF应用程序中使用UWP Toast通知。

  1. <TargetPlatformVersion>10.0</TargetPlatformVersion>添加到.csproj
  2. 如果您安装了任何软件包,请单击packages.config文件并选择Migrate packages.config to PackageReference...(重要步骤-这是我缺少的东西(
  3. 现在在Package Manager控制台中安装UWP.Notifications包,例如:Install-Package Microsoft.Toolkit.Uwp.Notifications -Version 7.0.2检查版本

现在,您应该能够使用所有uwp通知功能。

旧版:

正如@Andy在评论中所建议的那样,已经准备好了NuGet包的实现:github.com/Federer/Notifications.Wpf

如果你只想要一个没有onClick事件等的简单通知,你可以使用这个解决方案:

  1. <TargetPlatformVersion>10.0</TargetPlatformVersion>添加到.csproj
  2. 添加对Windows.UIWindows.Data的引用
  3. 添加以下用法:using Windows.Data.Xml.Dom; using Windows.UI.Notifications;
  4. 使用此代码显示通知:
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);

更多信息

此文档制作精良,请链接此处。

有关WPF应用程序的具体详细信息,请参阅Desktop(unpackaged)

最新更新