如何在显示h:m:s的wpf表单上显示时钟并每秒更新一次? [英] How to show a clock on a wpf form which shows h:m:s and updating every second?

查看:210
本文介绍了如何在显示h:m:s的wpf表单上显示时钟并每秒更新一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在wpf窗口上显示一个时钟,该时钟应该显示从我单击同一表格上的按钮(从00:00:00开始并每秒更新一次)起经过的时间.当某些事件发生时,它应该停止而不复位,而当我再次单击该按钮时,它应该复位并重新开始计时.

I want to show a clock on a wpf window, the clock should show the time passed from the moment when I click a button on the same form beginning from 00:00:00 and updating once a second. When some even occurs, it should stop without reset and when I click the button again it should reset and begin counting the time again.

有什么方法可以做到这一点?我应该使用简单的标签吗? 在我的应用程序中,我使用async并等待其他事情,应该为时钟使用什么,以及如何运行可以每秒使用一次处理程序"来更新时钟的方法?

What's an approach to accomplish this? Should I use a simple label? In my app I use async and await for other things, what should I use for the clock and how do I run a method which "handler" I can use for updating the clock once a second?

推荐答案

使用秒表.下面的代码将帮助您入门.

Use a StopWatch. The code below will get you started.

Stopwatch w = new Stopwatch();
DispatcherTimer timer;
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
    if (!w.IsRunning)
    {
        w.Start();

        if (timer == null )
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += timer_Tick;
        }
        timer.Start();
    }
}

void timer_Tick(object sender, EventArgs e)
{
    if (w.IsRunning)
    {                
        TbClock.Text = w.Elapsed.Hours + ":" + w.Elapsed.Minutes + ":" + w.Elapsed.Seconds;
        Debug.WriteLine(w.Elapsed.Hours + ":" + w.Elapsed.Minutes + ":" + w.Elapsed.Seconds);
    }
}

private void BtnEnd_Click(object sender, RoutedEventArgs e)
{
    if (w.IsRunning)
    {              
        w.Stop();
        w.Reset();

        timer.Stop();
    }
}

这篇关于如何在显示h:m:s的wpf表单上显示时钟并每秒更新一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆