Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show current time WPF

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.

like image 639
Vadim Ovchinnikov Avatar asked Jul 18 '26 14:07

Vadim Ovchinnikov


2 Answers

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");
}
[...]
like image 153
Marco Concas Avatar answered Jul 20 '26 05:07

Marco Concas


Here is a little code sample that works without a timer:

public DateTime CurrentTime
{
    get => DateTime.Now;
}

public CurrentViewModelTime(object sender, RoutedEventArgs e)
{
    _ = Update(); // calling an async function we do not want to await
}

private async Task Update()
{
    while (true)
    {
        await Task.Delay(100);
        OnPropertyChanged(nameof(CurrentTime)));
    }
}

Of course, this Update() function never returns, but it does its loop on a threadpool thread and does not even block any thread for long.

You can perfectly also implement this in the window directly without a viewmodel.

like image 42
J S Avatar answered Jul 20 '26 04:07

J S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!