To Make DateTime.Now Alive for WPF Data Binding

Given this XAML snippet:

<TextBlock DataContext="{x:Static sys:DateTime.Now}" Text="{Binding Now}" />

Appearantly, DateTime.Now is a static property which will not notify data binding engine to update its value. Now there are several ways to get it updated on every seconds.

Explicitly update the binding...

Create a timer on code-behind and update binding (thus UI) periodly explicitly...

// Code goes here...
1. Create Timer instance and set it to trigger update handle at specified interval
1. Get Binding instance from binding target object and target property
2. Explicitly call update method on the binding instance to update the value, manually.

Wrap DateTime into an active data object (say, LiveDateTime) which implements INotifyPropertyChanged and notify data binding engine on interval.

class LiveDateTime: INotifyPropertyChanged
{
  private Timer _timer;
  public event EventHandler PropertyChanged;

  public LiveDateTime()
  {
    _timer = new Timer(1000);
    _timer.Elapsed += delegate
    {
      if (PropertyChanged!=null) PropertyChanged(this, new PropertyChangedEventArgs("Now"))
    };
  }

  public DateTime Now { get { return DateTime.Now; } }
}

and on the XAML side:
  <local:LiveDateTime x:Key="liveDateTime" />
  <TextBlock Text={Binding Now, Source={StaticResource liveDateTime} } />

But a lazy programmer would dream of this one line of code to make it happen...

MakeAlive<DateTime>("Now", TimeSpan.FromSeconds(1));

or, use a declarative programming model:
[TargetType(typeof(DateTime))]
public class LivingDateTime
{
  [RefreshInterval(60)]
  public DateTime Now {get; set;}
}

That's exactly the initial purpose of this library.

Last edited May 10, 2009 at 11:19 AM by JGTM, version 4

Comments

No comments yet.