<Window x:Class="time2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:time2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Label Name="Label_OtherResult" HorizontalAlignment="Left" Margin="0,28,0,0" VerticalAlignment="Top" Height="300" Width="800" FontSize="120" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Background="CadetBlue" FontWeight="Bold"/>
<Button Content="开始" HorizontalAlignment="Left" Margin="197,359,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1" />
<Button Content="结束" HorizontalAlignment="Left" Margin="509,359,0,0" VerticalAlignment="Top" Click="Button_Click" Width="75"/>
</Grid>
</Window>
上面是界面代码,布局比较简单,没有太多的花里胡哨
public partial class MainWindow : Window
{
System.Timers.Timer timer;
public MainWindow()
{
InitializeComponent();
if (timer == null)
{
timer = new System.Timers.Timer();
timer.Interval = 1;
timer.Elapsed += timer_Elapsed;
}
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
this.Label_OtherResult.Content = DateTime.Now.ToString("%H:mm:s:fff");
}), null);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
timer.Start();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
timer.Close();
; }
这一块主要是使用了System.Timers.Timer而不是使用DispatcherTimer(distime),在刷新频率很高的情况下distime会有卡顿出现
tostring中是以小时:分钟:秒:毫秒的形式转换,正好做到的项目需求是毫秒后3位,时间格式这一块就不多赘述了