如何用C#實(shí)現(xiàn)自定義Toast消息

c#
小樊
83
2024-09-06 05:44:26

在C#中,你可以使用UWP(Universal Windows Platform)或WPF(Windows Presentation Foundation)應(yīng)用程序來(lái)實(shí)現(xiàn)自定義Toast消息

首先,確保已添加以下命名空間引用:

using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;

接下來(lái),創(chuàng)建一個(gè)用于生成和顯示自定義Toast消息的方法:

public void ShowCustomToast(string title, string message)
{
    // 創(chuàng)建XML模板
    string xmlString = $@"
        <toast>
           <visual>
               <binding template='ToastGeneric'>
                    <text>{title}</text>
                    <text>{message}</text>
                </binding>
            </visual>
        </toast>";

    // 將XML字符串解析為XmlDocument對(duì)象
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(xmlString);

    // 創(chuàng)建Toast通知
    ToastNotification toast = new ToastNotification(xmlDoc);

    // 獲取Toast通知管理器并顯示Toast
    ToastNotifier toastNotifier = ToastNotificationManager.CreateToastNotifier();
    toastNotifier.Show(toast);
}

現(xiàn)在,你可以調(diào)用此方法以顯示自定義Toast消息:

ShowCustomToast("Hello", "這是一個(gè)自定義Toast消息!");

請(qǐng)注意,此示例適用于UWP應(yīng)用程序。對(duì)于WPF應(yīng)用程序,你需要使用Microsoft.Toolkit.Uwp.Notifications庫(kù)。要使用該庫(kù),請(qǐng)安裝NuGet包:

Install-Package Microsoft.Toolkit.Uwp.Notifications

然后,你可以按照以下方式修改ShowCustomToast方法:

using Microsoft.Toolkit.Uwp.Notifications;

public void ShowCustomToast(string title, string message)
{
    // 創(chuàng)建Toast內(nèi)容
    var content = new ToastContent()
    {
        Visual = new ToastVisual()
        {
            BindingGeneric = new ToastBindingGeneric()
            {
                Children =
                {
                    new AdaptiveText()
                    {
                        Text = title
                    },
                    new AdaptiveText()
                    {
                        Text = message
                    }
                }
            }
        }
    };

    // 生成XML文檔
    var xmlDoc = content.GetXml();

    // 創(chuàng)建Toast通知
    var toast = new ToastNotification(xmlDoc);

    // 獲取Toast通知管理器并顯示Toast
    var toastNotifier = ToastNotificationManager.CreateToastNotifier();
    toastNotifier.Show(toast);
}

現(xiàn)在,你可以在WPF應(yīng)用程序中使用相同的方法調(diào)用來(lái)顯示自定義Toast消息。

0