Show current time WPF

Vadim Ovchinnikov picture Vadim Ovchinnikov · Jun 26, 2018 · Viewed 10.1k times · Source

The only way to show current time updating regularly I found is to use timer. Of course, I can implement INotifyPropertyChanged and some special property to be used on UI but this implementation AFAIK also needs Timer. For example like here. Are there any better way to display current time?

Edit

To clarify: are there any declarative way to make it work in real time without timer using XAML syntax like this?

<Label Content="{x:Static s:DateTime.Now}" ContentStringFormat="G" />

Nothing stops me from using timer here. I just want to know if there are more elegant and compact way of implementing this.

Answer

Marco Concas picture Marco Concas · Jan 7, 2019

Using Task.Delay can produce an high CPU usage!

In the XAML code write this:

<Label Name="LiveTimeLabel" Content="%TIME%" HorizontalAlignment="Left" Margin="557,248,0,0" VerticalAlignment="Top" Height="55" Width="186" FontSize="36" FontWeight="Bold" Foreground="Red" />

Next in the xaml.cs write this:

[...]
public MainWindow()
{
    InitializeComponent();
    DispatcherTimer LiveTime = new DispatcherTimer();
    LiveTime.Interval = TimeSpan.FromSeconds(1);
    LiveTime.Tick += timer_Tick;
    LiveTime.Start();
}

void timer_Tick(object sender, EventArgs e)
{
    LiveTimeLabel.Content = DateTime.Now.ToString("HH:mm:ss");
}
[...]