快顯通知進度列和資料繫結Toast progress bar and data binding

在快顯通知中使用進度列可以將長期執行的作業狀態傳達給使用者,例如下載、視訊呈現、練習目標等。Using a progress bar inside your toast notification allows you to convey the status of long-running operations to the user, like downloads, video rendering, exercise goals, and more.

重要

需要 Creators Update 和 Notifications 程式庫 1.4.0:您的目標必須是 SDK 15063 並執行組建 15063 或更高版本,才能在快顯通知上使用進度列。Requires Creators Update and 1.4.0 of Notifications library: You must target SDK 15063 and be running build 15063 or higher to use progress bars on toasts. 您必須使用版本 1.4.0 或更高版本的 UWP Community Toolkit Notifications NuGet 程式庫,以便在快顯通知內容中建構進度列。You must use version 1.4.0 or higher of the UWP Community Toolkit Notifications NuGet library to construct the progress bar in your toast's content.

快顯快顯中的進度列可以是「不定」 (沒有特定值、動畫的點表示作業發生) 或「確定」 (填滿特定的橫條百分比,例如 60% ) 。A progress bar inside a toast can either be "indeterminate" (no specific value, animated dots indicate an operation is occurring) or "determinate" (a specific percent of the bar is filled, like 60%).

重要 APINotificationData 類別ToastNotifier.Update 方法ToastNotification 類別Important APIs: NotificationData class, ToastNotifier.Update method, ToastNotification class

注意

僅桌上型電腦支援快顯通知中的進度列。Only Desktop supports progress bars in toast notifications. 在其他裝置上,會從您的通知捨棄進度列。On other devices, the progress bar will be dropped from your notification.

下圖顯示確定的進度列,並標示所有對應的屬性。The picture below shows a determinate progress bar with all of its corresponding properties labeled.

Toast with progress bar properties labeled
屬性Property 類型Type 必要Required 描述Description
標題Title 字串或 BindableStringstring or BindableString falsefalse 取得或設定選用標題字串。Gets or sets an optional title string. 支援資料繫結。Supports data binding.
ReplTest1Value double 或 AdaptiveProgressBarValueBindableProgressBarValuedouble or AdaptiveProgressBarValue or BindableProgressBarValue falsefalse 取得或設定進度列的值。Gets or sets the value of the progress bar. 支援資料繫結。Supports data binding. 預設為 0。Defaults to 0. 可以是之間 0.0 和 1.0 之間的 double、AdaptiveProgressBarValue.Indeterminatenew BindableProgressBarValue("myProgressValue")Can either be a double between 0.0 and 1.0, AdaptiveProgressBarValue.Indeterminate, or new BindableProgressBarValue("myProgressValue").
ValueStringOverrideValueStringOverride 字串或 BindableStringstring or BindableString falsefalse 取得或設定要顯示的選用字串,用於取代預設百分比字串。Gets or sets an optional string to be displayed instead of the default percentage string. 如果未提供此項,將會顯示「70%」之類的內容。If this isn't provided, something like "70%" will be displayed.
狀態Status 字串或 BindableStringstring or BindableString truetrue 取得或設定狀態字串 (必要),它會顯示在左側進度列的下方。Gets or sets a status string (required), which is displayed underneath the progress bar on the left. 這個字串應該反映作業的狀態,例如「正在下載...」或「正在安裝...」This string should reflect the status of the operation, like "Downloading..." or "Installing..."

以下是產生上方所見通知的方式...Here's how you would generate the notification seen above...

new ToastContentBuilder()
    .AddText("Downloading your weekly playlist...")
    .AddVisualChild(new AdaptiveProgressBar()
    {
        Title = "Weekly playlist",
        Value = 0.6,
        ValueStringOverride = "15/26 songs",
        Status = "Downloading..."
    });

不過,您需要動態更新進度列的值,進度列才能看起來是「活動的」。However, you'll need to dynamically update the values of the progress bar for it to actually be "live". 做法是使用資料繫結來更新快顯通知。This can be done by using data binding to update the toast.

使用資料繫結來更新快顯通知Using data binding to update a toast

使用資料繫結包含下列步驟...Using data binding involves the following steps...

  1. 建構可使用資料繫結欄位的快顯通知內容Construct toast content that utilizes data bound fields
  2. 指派 Tag (也可以是 Group) 到您的 ToastNotificationAssign a Tag (and optionally a Group) to your ToastNotification
  3. 定義您 ToastNotification 的初始 DataDefine your initial Data values on your ToastNotification
  4. 傳送快顯通知Send the toast
  5. 使用 TagGroup,以新值更新 Data 的值Utilize Tag and Group to update the Data values with new values

下列程式碼片段顯示步驟 1-4。The following code snippet shows steps 1-4. 下一個程式碼片段顯示如何更新快顯通知的 Data 值。The next snippet will show how to update the toast Data values.

using Windows.UI.Notifications;
using Microsoft.Toolkit.Uwp.Notifications;
 
public void SendUpdatableToastWithProgress()
{
    // Define a tag (and optionally a group) to uniquely identify the notification, in order update the notification data later;
    string tag = "weekly-playlist";
    string group = "downloads";
 
    // Construct the toast content with data bound fields
    var content = new ToastContentBuilder()
        .AddText("Downloading your weekly playlist...")
        .AddVisualChild(new AdaptiveProgressBar()
        {
            Title = "Weekly playlist",
            Value = new BindableProgressBarValue("progressValue"),
            ValueStringOverride = new BindableString("progressValueString"),
            Status = new BindableString("progressStatus")
        })
        .GetToastContent();
 
    // Generate the toast notification
    var toast = new ToastNotification(content.GetXml());
 
    // Assign the tag and group
    toast.Tag = tag;
    toast.Group = group;
 
    // Assign initial NotificationData values
    // Values must be of type string
    toast.Data = new NotificationData();
    toast.Data.Values["progressValue"] = "0.6";
    toast.Data.Values["progressValueString"] = "15/26 songs";
    toast.Data.Values["progressStatus"] = "Downloading...";
 
    // Provide sequence number to prevent out-of-order updates, or assign 0 to indicate "always update"
    toast.Data.SequenceNumber = 1;
 
    // Show the toast notification to the user
    ToastNotificationManager.CreateToastNotifier().Show(toast);
}

接著,當您想要變更 Data 值,請使用 Update 方法來提供新的資料,而不需要重新建構整個快顯通知承載。Then, when you want to change your Data values, use the Update method to provide the new data without re-constructing the entire toast payload.

using Windows.UI.Notifications;
 
public void UpdateProgress()
{
    // Construct a NotificationData object;
    string tag = "weekly-playlist";
    string group = "downloads";
 
    // Create NotificationData and make sure the sequence number is incremented
    // since last update, or assign 0 for updating regardless of order
    var data = new NotificationData
    {
        SequenceNumber = 2
    };

    // Assign new values
    // Note that you only need to assign values that changed. In this example
    // we don't assign progressStatus since we don't need to change it
    data.Values["progressValue"] = "0.7";
    data.Values["progressValueString"] = "18/26 songs";

    // Update the existing notification's data by using tag/group
    ToastNotificationManager.CreateToastNotifier().Update(data, tag, group);
}

使用 Update 方法而非更換整個快顯通知,也可確保快顯通知停在控制中心的相同位置而不會向上或向下移動。Using the Update method rather than replacing the entire toast also ensures that the toast notification stays in the same position in Action Center and doesn't move up or down. 如果因為填入進度列而使得快顯通知每隔幾秒就跳到控制中心的頂端,會令使用者感到相當困惑!It would be quite confusing to the user if the toast kept jumping to the top of Action Center every few seconds while the progress bar filled!

Update 方法會傳回列舉 NotificationUpdateResult,這可讓您知道更新是否成功或是否找不到通知 (這表示使用者可能已關閉通知,因此您應該停止傳送更新)。The Update method returns an enum, NotificationUpdateResult, which lets you know whether the update succeeded or whether the notification couldn't be found (which means the user has likely dismissed your notification and you should stop sending updates to it). 在進度作業完成 (例如下載完成) 前,不建議您彈出另一個快顯通知。We do not recommend popping another toast until your progress operation has been completed (like when the download completes).

支援資料繫結的元素Elements that support data binding

快顯通知中的下列元素支援資料繫結The following elements in toast notifications support data binding

  • AdaptiveProgress 上的所有屬性All properties on AdaptiveProgress
  • 最上層 AdaptiveText 元素上的 Text 屬性The Text property on the top-level AdaptiveText elements

更新或更換通知Update or replace a notification

從 Windows 10 開始,您一律可以藉由傳送具有相同 TagGroup 的新快顯通知來取代通知。Since Windows 10, you could always replace a notification by sending a new toast with the same Tag and Group. 那麼,更換快顯通知和更新快顯通知資料有何不同?So what's the difference between replacing the toast and updating the toast's data?

更換Replacing 更新Updating
控制中心中的位置Position in Action Center 通知會移到控制中心的頂端。Moves the notification to the top of Action Center. 通知停留在控制中心的相同位置。Leaves the notification in place within Action Center.
修改內容Modifying content 完全可以變更快顯通知的所有內容/配置Can completely change all content/layout of the toast 只能變更支援資料繫結的屬性 (進度列和最上層的文字)Can only change properties that support data binding (progress bar and top-level text)
以快顯視窗方式重新出現Reappearing as popup 若保留 SuppressPopup 設定為 false 可以快顯通知快顯方式重新出現 (或設定為 true,則以無訊息方式傳送至控制中心)Can reappear as a toast popup if you leave SuppressPopup set to false (or set to true to silently send it to Action Center) 不會以快顯視窗方式重新出現;快顯通知資料以無訊息方式在控制中心內更新Won't reappear as a popup; the toast's data is silently updated within Action Center
使用者關閉User dismissed 無論使用者是否關閉您先前的通知,一律會傳送更換快顯通知Regardless of whether user dismissed your previous notification, your replacement toast will always be sent 如果使用者關閉您的快顯通知,快顯通知更新將會失敗If the user dismissed your toast, the toast update will fail

一般而言,更新適用於...In general, updating is useful for...

  • 在短時間內頻繁變更,且不需要吸引使用者注意的資訊Information that frequently changes in a short period of time and doesn't require being brought to the front of the user's attention
  • 快顯通知內容的細微變更,例如從 50% 變更到 65%Subtle changes to your toast content, like changing 50% to 65%

很多時候,在完成更新系列之後 (例如檔案已下載),建議您在最後一個步驟進行更換,因為...Often times, after your sequence of updates have completed (like the file has been downloaded), we recommend replacing for the final step, because...

  • 最後通知可能有大幅配置變更,例如移除進度列、新增新的按鈕等Your final notification likely has drastic layout changes, like removal of the progress bar, addition of new buttons, etc
  • 使用者可能已關閉擱置中的進度通知,因為他們不在意觀看下載過程,但仍想在作業完成時獲得快顯視窗的通知The user might have dismissed your pending progress notification since they don't care about watching it download, but still want to be notified with a popup toast when the operation is completed