使用定时器制作一个显示时间的效果,如下所示:
UI布局如下所示:
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock x:Name="txt" FontSize="100" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<StackPanel
Grid.Row="1"
HorizontalAlignment="Center"
Orientation="Horizontal">
<Button
x:Name="start"
Width="120"
Height="30"
Margin="10"
Content="开始" Click="Button_Click" />
<Button
x:Name="stop"
Width="120"
Height="30"
Margin="10"
Content="暂停"
IsEnabled="False" Click="btn_Click"/>
</StackPanel>
</Grid>
后台代码如下所示:
using System;
using System.Windows;
using System.Windows.Threading;
namespace TheadPoolDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(100); // 100ms 更新一次
dispatcherTimer.Tick += DispatcherTimer_Tick;
}
DispatcherTimer dispatcherTimer = null;
private void DispatcherTimer_Tick(object sender, EventArgs e)
{
this.txt.Text = DateTime.Now.ToString("HH:mm:ss");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
dispatcherTimer.Start();
this.start.IsEnabled = false;
this.stop.IsEnabled = true;
}
private void btn_Click(object sender, RoutedEventArgs e)
{
dispatcherTimer.Stop();
this.stop.IsEnabled = false;
this.start.IsEnabled = true;
}
}
}