#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.

Follow

Get every new post delivered to your Inbox.

Join 369 other followers