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?
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.
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");
}
[...]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With