使用集合來整理應用程式的通知在通知中心。 集合功能幫助使用者更輕鬆地找到資訊,並讓開發者能更好地管理通知。
例如,訊息應用程式可以依群組分隔通知。 每個群組名稱(「電腦科學 160A 專案聊天」、「直接訊息」、「長曲棍球團隊聊天」)都是獨立的集合。 通知被分組成若來自一個獨立的應用程式,儘管它們都來自同一個應用程式。 想要更細膩地組織通知,請參考 應用程式通知標頭。
具有兩個不同通知群組的 
備註
本文的程式碼範例使用 Microsoft.Windows.AppNotifications 命名空間來建立通知內容,並使用 Windows.UI.Notifications 命名空間來管理集合。 這兩個命名空間可以在同一個應用程式中一起使用。
欲了解更多關於應用程式通知的資訊,請參閱 應用程式通知總覽。
建立集合
建立收藏時,請提供顯示名稱和圖示,這些名稱會在通知中心作為收藏標題的一部分顯示。 收藏也需要啟動參數,讓應用程式在使用者點擊集合標題時能導向正確位置。 請透過呼叫 SaveToastCollectionAsync 建立該收藏。
using Windows.UI.Notifications;
var collection = new ToastCollection(
"MyToastCollection",
"Work Email",
"NavigateToWorkEmailInbox",
new Uri("ms-appx:///Assets/workEmail.png"));
await ToastNotificationManager.GetDefault()
.GetToastCollectionManager()
.SaveToastCollectionAsync(collection);
向集合發送通知
使用 AppNotificationBuilder 來建構通知內容,然後呼叫 GetToastNotifierForToastCollectionIdAsync 來取得一個針對該集合的通知視窗。
using Microsoft.Windows.AppNotifications.Builder;
using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;
// Build notification content with Windows App SDK
var payload = new AppNotificationBuilder()
.AddText("Adam sent a message to the group")
.BuildNotification()
.Payload;
// Deliver to a collection using the WinRT API
var doc = new XmlDocument();
doc.LoadXml(payload);
var toast = new ToastNotification(doc);
var notifier = await ToastNotificationManager.GetDefault()
.GetToastNotifierForToastCollectionIdAsync("MyToastCollection");
notifier.Show(toast);
列出所有集合
請透過呼叫 FindAllToastCollectionsAsync 取得所有為你應用程式建立的收藏。
var collectionManager = ToastNotificationManager.GetDefault().GetToastCollectionManager();
var collections = await collectionManager.FindAllToastCollectionsAsync();
更新集合
透過建立一個具有相同 ID 的新 ToastCollection 實例並呼叫 SaveToastCollectionAsync,來更新收藏。
var collectionManager = ToastNotificationManager.GetDefault().GetToastCollectionManager();
var updatedCollection = new ToastCollection(
"MyToastCollection",
"Updated Display Name",
"UpdatedLaunchArgs",
new Uri("ms-appx:///Assets/updatedPicture.png"));
await collectionManager.SaveToastCollectionAsync(updatedCollection);
移除集合
透過呼叫 RemoveToastCollectionAsync 並附上收藏 ID 來移除收藏。 收藏中的任何通知也會從通知中心移除。
var collectionManager = ToastNotificationManager.GetDefault().GetToastCollectionManager();
await collectionManager.RemoveToastCollectionAsync("MyToastCollection");
移除集合內的通知
使用 Tag 和 Group 屬性,透過呼叫「 移除」來識別並移除集合中的個別通知,或用 「清除」一次性清除所有通知。
var collectionHistory = await ToastNotificationManager.GetDefault()
.GetHistoryForToastCollectionAsync("MyToastCollection");
// Remove a specific notification
collectionHistory.Remove(tag, group);
// Or clear all notifications in the collection
collectionHistory.Clear();