c# - 显示当前时间 WPF

标签 c# wpf xaml real-time current-time

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

相关文章:

c# - WPF 错误 40 BindingExpression 路径错误 : property not found on 'object'

xaml - UWP ToggleSwitch 将内容放在左侧

c# - 具有透明状态栏的 Xamarin Forms 背景图像

c# - WPF 中的键值对组合框

c# - 我如何对 ICommands 进行分组,以便如果一个正在执行,其他则不能?

c# - 6.12.0 unity sdk是不是没有continuation action "ContinueWithOnMainThread"?

c# - XmlSerializer 添加属性

c# - WPF 控件的嵌套属性的数据绑定(bind)

c# - System.Windows.Controls.Canvas 到 System.Windows.Controls.TextBox 的无效转换异常

c# - 从 F# 使用 UWP 应用服务