如何在UWP App中创建信息丰富的Toast通知

在我的应用程序中,我想告知用户何时执行了特定操作,例如记录更新成功或添加了新记录,但是没有内置控件可以显示此类信息。 是否有类似于UWP的Android Toast.makeText?

是的,UWP有Toast Notifications 🙂

以下是显示简单通知的示例代码:

private void ShowToastNotification(string title, string stringContent) { ToastNotifier ToastNotifier = ToastNotificationManager.CreateToastNotifier(); Windows.Data.Xml.Dom.XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02); Windows.Data.Xml.Dom.XmlNodeList toastNodeList = toastXml.GetElementsByTagName("text"); toastNodeList.Item(0).AppendChild(toastXml.CreateTextNode(title)); toastNodeList.Item(1).AppendChild(toastXml.CreateTextNode(stringContent)); Windows.Data.Xml.Dom.IXmlNode toastNode = toastXml.SelectSingleNode("/toast"); Windows.Data.Xml.Dom.XmlElement audio = toastXml.CreateElement("audio"); audio.SetAttribute("src", "ms-winsoundevent:Notification.SMS"); ToastNotification toast = new ToastNotification(toastXml); toast.ExpirationTime = DateTime.Now.AddSeconds(4); ToastNotifier.Show(toast); } 

在本文中,您可以找到如何自定义它:

https://docs.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-adaptive-interactive-toasts

这里如何实现像android这样简单的makeText:

  private Windows.UI.Xaml.Controls.Frame frame; private Windows.UI.Xaml.Controls.Page page; private Ribo.Smart.App.UserControls.Components.Common.Toast toast; private DispatcherTimer timer = new DispatcherTimer(); void timer_Tick(object sender, object e) { if (toast != null) ((Panel)page.FindName("layoutRoot")).Children.Remove(toast); toast = null; timer.Stop(); timer.Tick -= timer_Tick; } private void Frame_Navigated(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e) { if (toast != null) { object layoutRoot = page.FindName("layoutRoot"); if (layoutRoot != null) { ((Panel)layoutRoot).Children.Remove(toast); page = (Windows.UI.Xaml.Controls.Page)e.Content; layoutRoot = page.FindName("layoutRoot"); ((Panel)layoutRoot).VerticalAlignment = VerticalAlignment.Stretch; ((Panel)layoutRoot).Children.Add(toast); if (layoutRoot is Grid) { toast.SetValue(Grid.RowSpanProperty, 100); } } } } public void ShowMessage(string message) { frame = (Windows.UI.Xaml.Controls.Frame)Windows.UI.Xaml.Window.Current.Content; page = (Windows.UI.Xaml.Controls.Page)frame.Content; frame.Navigated -= Frame_Navigated; frame.Navigated += Frame_Navigated; toast = new Ribo.Smart.App.UserControls.Components.Common.Toast(); toast.Message = message; toast.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Bottom; toast.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center; int seconds = message.Length / 30; if (seconds < 2) seconds = 2; timer.Interval = new TimeSpan(0, 0, seconds); timer.Start(); timer.Tick -= timer_Tick; timer.Tick += timer_Tick; object layoutRoot = page.FindName("layoutRoot"); if (layoutRoot != null) { if (layoutRoot is Grid) { toast.SetValue(Grid.RowSpanProperty, 100); } ((Panel)layoutRoot).Children.Add(toast); } }