WPF弹出一个窗口,并自动关闭

最近用WPF做了一个小的demo,由于对于WPF不是很熟悉,在这个过程中遇到不少问题,这篇文章便是针对某个小需求的整理,这个需求便是:在WPF中,如何弹出一个窗口,并让它定时自动关闭

我记得我最早的思路是在主窗口中开启一个线程,这个线程每隔1s休眠一次,用这个线程来控制窗口的显示和隐藏。那个时候,我不知道WPF中,有一个叫做Timer的类。可想而知,这调试过程是多么艰难与纠结……

然而,它用Timer来实现,却是如此简单,用以下的小case来展示它的实现:主窗口上一个按钮,点击按钮,弹出一个窗口,窗口中显示一段文字,窗口3秒后自动关闭。

 

主窗口代码:

<Window x:Class="TestForWpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="517" Width="842" Background="White" WindowStartupLocation="CenterScreen">
    <Grid>
        <Button Content="Pop up" Height="23" HorizontalAlignment="Left" Margin="58,38,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>
</Window>

后台代码:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            PopupWindow win = new PopupWindow();
            win.Show();
        }
    }


弹出窗口代码:

<Window x:Class="TestForWpf.PopupWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PopupWindow" Height="211" Width="401" ResizeMode="NoResize" WindowStyle="None" WindowStartupLocation="CenterScreen">
    <Grid Background="#dedede" Height="152" Width="359">
        <Label Margin="46,44,54,54" Height="40" Content="This is a self-closing window!" VerticalContentAlignment="Bottom" FontSize="18" FontWeight="Bold"></Label>
    </Grid>
</Window>


后台代码:

    /// <summary>
    /// Interaction logic for PopupWindow.xaml
    /// </summary>
    public partial class PopupWindow : Window
    {
        private Timer timer = new Timer(3000);
        public PopupWindow()
        {
            InitializeComponent();

            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            timer.Stop();
            Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate()
            {
                this.Hide();
            });
        }
    }


效果图:


 

    

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值