C# WPF 仿 Android Toast 效果

转载请注明出处: https://blog.csdn.net/hx7013/article/details/142860084

主职Android, 最近需要写一些WPF的程序作为上位机,目前WPF的MessageBox过于臃肿,且想找一个内置的非阻塞的简单提示一直找不到,想到了Android的Toast所以写了这个扩展方法。
调用简单,一行代码调用 this.ShowToast("") ,支持自定义关闭时间,手动关闭,文本颜色、背景颜色等。做了非主线程调用的处理,参数也加了注释方便个人扩充。

效果演示

https://blog.csdn.net/hx7013
https://blog.csdn.net/hx7013

代码

使用

记得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;
                }

                // 自动关闭 Popup
                if (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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值