簡體   English   中英

如何在 WPF 應用程序中集成 Toast 通知?

[英]How can I integrate toast notifications in WPF app?

我想向我的 wpf 應用程序添加吐司通知。

我已經按照從 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);

此外,我已將<TargetPlatformVersion>10.0</TargetPlatformVersion>到 .csproj,引用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'

我該如何解決?

請注意,我也嘗試使用'ready example' ,但結果相同。

新的:

有一種在 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.UIWindows.Data引用
  3. 添加以下用途: using Windows.Data.Xml.Dom; using Windows.UI.Notifications; 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);

更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM