#370 – Binding a Label’s Content to the Current Date and Time, part II
August 23, 2011 4 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"));
}

Pingback: Dew Drop–August 23, 2011 | Alvin Ashcraft's Morning Dew
Hi Sean, Great series of examples.
When I first tried the code example, it wasn’t immediately obvious that my Window needed to implement INotifyPropertyChanged and specifically
public event PropertyChangedEventHandler PropertyChanged;
Just thought it was worth mentioning for anyone that might not realise
Great Tip
(Little note about terminology. The author didn’t use a dependency property but used the INotifyPropertyChanged interface)
Thanks, good catch–I described one thing and implemented something different. Updated the post to fix this.