KField KField - 4 months ago 27
C# Question

Show a running timer in a WPF window

I am new to WPF and I am working on a project which needs to show a running timer on the window. The page with the timer is showing the detail information of a test, such as ID, test name, status, start time, end time, blahblahblah...

I really wish that I could have a timer on the page that tells the user that how long the test has been running. But I didn't find a tool in the toolbox which can show a running timer and I don't even know how to put moving stuff on the page...

Could you guys tell me how to add a running timer on the page?

In addition, if this is possible, I wish my timer could start from some specific time instead of 00:00:00. The reason I need this is because the user can open this page when the test has been running for a while, and the elapsed time shown on the timer should be (current_time - start_time) and start from here.

If the test start at: 7:00 AM and the user opens the page at 7:05AM and the test is still running, the timer should start from 00:05:00.

Thank you so much, guys! Hope this long description won't make you bored:)


Here is a very basic example I threw together.

using System.Windows.Threading;

namespace BasicTimer
    public partial class MainWindow : Window
        DispatcherTimer t;
        DateTime start;
        public MainWindow()
            t = new DispatcherTimer(new TimeSpan(0, 0, 0, 0, 50), DispatcherPriority.Background,
                t_Tick, Dispatcher.CurrentDispatcher); t.IsEnabled = true;
            start = DateTime.Now;

        private void t_Tick(object sender, EventArgs e)
            TimerDisplay.Text = Convert.ToString(DateTime.Now - start);

MainWindow XAML

<Window x:Class="BasicTimer.MainWindow"
        Title="MainWindow" Height="100" Width="200">
        <TextBlock x:Name="TimerDisplay" HorizontalAlignment="Left"/>