WPF使用Timer实现计时器

<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位,时间格式这一块就不多赘述了

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值