你可以通过绑定Label控件的Content属性到DateTime.Now属性显示当前的日期和时间,但是如果仅仅是直接绑定,时间是不会自动更新的。
需要显示时间持续更新,你需要绑定一个可以持续通过INotifyPropertyChanged 接口通知改变的属性。这个我们可以通过一个计时器来实现。
XAML代码:
<Label Content="{Binding CurrentDateAndTime}" ContentStringFormat="Current time - {0:T}"/>
在C#代码中,我们定义一个属性表示显示的时间,并且开启计时器Timer:
public DateTime CurrentDateAndTime { get; set; }
public MainWindow()
{
this.InitializeComponent();
this.DataContext = this;
DispatcherTimer dayTimer = new DispatcherTimer();
dayTimer.Interval = TimeSpan.FromMilliseconds(500);
dayTimer.Tick += new EventHandler(dayTimer_Tick);
dayTimer.Start();
}
每当计时器触发,我们就更新定义的属性的值并发送INotifyPropertyChanged.PropertyChanged 事件。
void dayTimer_Tick(object sender, EventArgs e)
{
CurrentDateAndTime = DateTime.Now;
PropertyChanged(this, new PropertyChangedEventArgs("CurrentDateAndTime"));
}
结果如下: