显示当前时间WPF [英] Show current time WPF

查看:102
本文介绍了显示当前时间WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显示我发现的定期更新当前时间的唯一方法是使用计时器.当然,我可以实现 INotifyPropertyChanged 和一些要在UI上使用的特殊属性,但是此实现AFAIK也需要 Timer .例如,此处.还有什么更好的方法来显示当前时间?

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?

要澄清一下:是否有任何声明性的方法可以使用这样的XAML语法不使用计时器实时运行它?

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.

推荐答案

使用Task.Delay可能会提高CPU使用率!

在XAML代码中输入以下内容:

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" />

接下来在xaml.cs中编写以下代码:

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

这篇关于显示当前时间WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆