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");
}
[...]