最近用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();
});
}
}
效果图: