转载请注明出处: https://blog.csdn.net/hx7013/article/details/142860084
主职Android, 最近需要写一些WPF的程序作为上位机,目前WPF的MessageBox过于臃肿,且想找一个内置的非阻塞的简单提示一直找不到,想到了Android的Toast所以写了这个扩展方法。
调用简单,一行代码调用 this.ShowToast("")
,支持自定义关闭时间,手动关闭,文本颜色、背景颜色等。做了非主线程调用的处理,参数也加了注释方便个人扩充。
效果演示
代码
使用
记得using扩展方法
public partial class TestWindow : Window{public TestWindow(){InitializeComponent();}private void BTN_TestToast_Click(object sender, RoutedEventArgs e){this.ShowToast("仿 Android Toast\n这里是手动换行\n这里是过长后自动换行(1234567890ABCDEFGHIJKLMN)");}}
Toast扩展方法
using System.Windows.Controls.Primitives;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Windows;
using System.Windows.Media;namespace WinManage
{public static class UIExtensions{/// <summary>/// 最后一次Toast/// </summary>private static Popup? lastToast = null;/// <summary>/// Toast 提示/// https://blog.csdn.net/hx7013/// </summary>/// <param name="target">目标窗口</param>/// <param name="message">消息内容</param>/// <param name="single">是否单例显示(true 会自动关闭上一个单例的Popup)</param>/// <param name="duration">显示时长(秒), >0则自动关闭, <=0 则需手动关闭</param>/// <param name="fontSize">字体大小</param>/// <param name="textColor">文本颜色</param>/// <param name="background">背景</param>/// <returns>Popup: 外部可使用 Popup.IsOpen = false; 手动关闭</returns>public static Popup ShowToast(this Window target, string message, bool single = true, int duration = 2, double fontSize = 15, Brush? textColor = null, Brush? background = null){Popup show(){TextBlock textBlock = new(){Text = message,FontSize = fontSize,Padding = new Thickness(12, 0, 12, 0),MaxWidth = 320,TextWrapping = TextWrapping.Wrap,Foreground = textColor ?? Brushes.White,HorizontalAlignment = HorizontalAlignment.Center,VerticalAlignment = VerticalAlignment.Center};Border border = new(){Background = background ?? new SolidColorBrush(Color.FromArgb(200, 0, 0, 0)),CornerRadius = new CornerRadius(10),Padding = new Thickness(10),Child = textBlock};// 测量文本的实际大小border.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));double actualTextWidth = border.DesiredSize.Width;double horizontalOffset = (target.Width + actualTextWidth) / 2;Popup toast = new(){Placement = PlacementMode.Relative,PlacementTarget = target,HorizontalOffset = horizontalOffset,VerticalOffset = target.Height - 128,AllowsTransparency = true,Child = border,IsOpen = true,};if (single){var localLastToast = lastToast;if (localLastToast != null){localLastToast.IsOpen = false;lastToast = null;}lastToast = toast;}// 自动关闭 Popupif (duration > 0){DispatcherTimer timer = new(){Interval = TimeSpan.FromSeconds(duration)};timer.Tick += (s, e) =>{if (toast != null && toast.IsOpen){toast.IsOpen = false;}timer.Stop();};timer.Start();}return toast;}var dispatcher = Application.Current.Dispatcher;if (dispatcher.CheckAccess()){return show();}else{return dispatcher.Invoke(() => show());}}}
}
转载请注明出处: https://blog.csdn.net/hx7013/article/details/142860084