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

编辑

需要说明的是:是否有任何声明性方法可以使用XAML语法使它实时运行而无需使用计时器?

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


没有什么可以阻止我在这里使用计时器。我只想知道是否有更优雅,更紧凑的实现方法。

最佳答案

使用Task.Delay会产生很高的CPU使用率!

在XAML代码中编写以下代码:

<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中编写以下代码:

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

关于c# - 显示当前时间WPF,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51039348/

10-17 01:23