#370 – Binding a Label’s Content to the Current Date and Time, part II

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"));
        }

The end result:

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

8 Responses to #370 – Binding a Label’s Content to the Current Date and Time, part II

  1. Pingback: Dew Drop–August 23, 2011 | Alvin Ashcraft's Morning Dew

  2. AndyS says:

    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 🙂

  3. coolbaldyTom says:

    Great Tip

    (Little note about terminology. The author didn’t use a dependency property but used the INotifyPropertyChanged interface)

  4. Pathdrc says:

    I have one problem. I get an error: “The name ‘PropertyChanged’ does not exist in the current context”
    I am a noob programmer. (I did really well programming Applesoft Basic and machine code back in the 80’s, but nothing until just recently I started learning C#.)
    Using Visual C# 2010 Express
    .NET Framework version 4 SP1
    Probably doesn’t matter but OS is WIN XP.

    C#

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Windows.Threading;
    using System.ComponentModel;

    namespace WpfClock
    {
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
    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();
    }
    void dayTimer_Tick(object sender, EventArgs e)
    {
    CurrentDateAndTime = DateTime.Now;

    PropertyChanged(this, new PropertyChangedEventArgs(“CurrentDateAndTime”));
    }
    }
    }

    XAML

  5. RobiGo says:

    I have implemented what is described above + this:

    public event PropertyChangedEventHandler PropertyChanged;

    And I get this error in runtime:

    An unhandled exception of type ‘System.NullReferenceException’ occurred…

    and the cursor is stay after this line:

    PropertyChanged(this, new PropertyChangedEventArgs(“CurrentDateAndTime”));

    Any idea?

    • Sean says:

      The exception is telling you that PropertyChanged is null. You could verify this in the debugger. This indicates that you have no subscribers to the event. When firing the event, you can either check for null before invoking it or you can initialize the event to point to an empty delegate list so that there is always at least one handler. (Just set the event to delegate {} )

Leave a comment