我发现定期更新显示当前时间的唯一方法是使用计时器。当然,我可以实现 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/