#369 – Binding a Label’s Content to the Current Date and Time

You can use data binding to assign the current date and time to a Label control.

You start by creating an instance of a DateTime object using the ObjectDataProvider tag.

    <Window.Resources>
        <ObjectDataProvider x:Key="today" ObjectType="{x:Type sys:DateTime}"/>
    </Window.Resources>

Note that we’re using a sys: prefix, which requires the following namespace declaration.

    xmlns:sys="clr-namespace:System;assembly=mscorlib"

We can now use data binding to bind to the DateTime.Now property.

        <Label Content="{Binding Source={StaticResource today}, Path=Now}" ContentStringFormat="Today is {0:D}"
               HorizontalContentAlignment="Center" Padding="10"/>
        <Label Content="{Binding Source={StaticResource today}, Path=Now}" ContentStringFormat="The time is {0:t}"
               HorizontalContentAlignment="Center" Padding="10"/>

The result will look like this:

This solution is not very good, since the binding happens just once, when the application starts.  Neither label will update when the date or time changes.  A better solution would be to bind to a property in a class that changes periodically, using the INotifyPropertyChanged interface.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: