首页 > 解决方案 > 如何在 WPF 应用程序中集成 toast 通知?

问题描述

我想向我的 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);

另外,我在 .csproj 中添加了对,<TargetPlatformVersion>10.0</TargetPlatformVersion>的引用。Windows.DataWindows.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我收到以下错误:

The type 'ToastNotification' exists in both 'Windows.Foundation.UniversalApiContract, Version=8.0.0.0, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime' and 'Windows.UI, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime'

我该如何解决?

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

标签: c#wpf

解决方案


新的:

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

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

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

老的:

正如@Andy 在评论中建议的那样,有现成的 NuGet 包实现:github.com/Federerer/Notifications.Wpf

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

  1. 添加<TargetPlatformVersion>10.0</TargetPlatformVersion>到 .csproj
  2. 添加对Windows.UI和的引用Windows.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);

更多信息


推荐阅读