C# 自定义倒计时MessageBox

首先需要设计一个简单的界面,一个label和button,如图所示。
在这里插入图片描述
UI核心代码如下:

    <Grid>
        <Label x:Name="lb_content" Content="Label" HorizontalAlignment="Left" Margin="76,68,0,0" VerticalAlignment="Top" Height="126" Width="322" FontSize="16"/>
        <Button  x:Name="bt_submit" Content="确定" HorizontalAlignment="Left" Margin="204,222,0,0" VerticalAlignment="Top" Width="74" Click="Bt_submit_Click"/>
    </Grid>

交互逻辑代码如下:

/// <summary>
    /// DiyMessageBox.xaml 的交互逻辑
    /// </summary>
    public partial class DiyMessageBox : Window
    {
        private int count = 0;
        private System.Threading.Timer timer;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="content">显示内容</param>
        public DiyMessageBox(string content)
        {
            InitializeComponent();
            lb_content.Content = content;
            //居中弹出
            this.Left = System.Windows.SystemParameters.PrimaryScreenWidth / 2 - this.Width / 2;
            this.Top = System.Windows.SystemParameters.PrimaryScreenHeight / 2 - this.Height / 2;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="content">显示内容</param>
        /// <param name="count">计数值</param>
        public DiyMessageBox(string content, int count)
        {
            InitializeComponent();
            lb_content.Content = content;
            this.count = count;
            timer = new System.Threading.Timer(TimerFunction, null, 0, 1000);
            //居中弹出
            this.Left = System.Windows.SystemParameters.PrimaryScreenWidth / 2 - this.Width / 2;
            this.Top = System.Windows.SystemParameters.PrimaryScreenHeight / 2 - this.Height / 2;
        }

        private void TimerFunction(object state)
        {
            Console.WriteLine(count);
            this.Dispatcher.Invoke(new Action(() => { bt_submit.Content = $"确定({count})"; }));
            if (count < 0)
            {
                timer.Dispose();
                this.Dispatcher.Invoke(new Action(() => { this.Close(); }));
            }
            count--;
        }

        private void Bt_submit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值