#370 – Binding a Label’s Content to the Current Date and Time, part II
August 23, 2011 6 Comments
You can bind a Label control’s Content property to the DateTime.Now property to display the current date or time, but the label will not update when the time changes.
To get a Label control that continuously updates with the current time, you can bind to a property that updates periodically and notifies us using the INotifyPropertyChanged interface. We can do this by creating a timer that updates a DateTime property whenever it ticks.
Here’s the XAML:
<Label Content="{Binding CurrentDateAndTime}" ContentStringFormat="Current time - {0:T}"/>
In the code-behind, we define the property and set up a 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();
}
Whenever the timer fires, we update our property and fire the INotifyPropertyChanged.PropertyChanged event.
void dayTimer_Tick(object sender, EventArgs e)
{
CurrentDateAndTime = DateTime.Now;
PropertyChanged(this, new PropertyChangedEventArgs("CurrentDateAndTime"));
}
