views:

248

answers:

1

I want to show the user how many seconds have passed since some event occurs. Conceptually, my view model has properties like this:

public DateTime OccurredAtUtc { get; set; }

public int SecondsSinceOccurrence
{
    get { return (int)(DateTime.UtcNow - OccurredAtUtc).TotalSeconds; }
}

If I bind a TextBlock.Text property to SecondsSinceOccurrence, the value appears but it is static. The passing of time does not reflect the increasing age of this event.

<!-- static value won't update as time passes -->
<TextBlock Text="{Binding SecondsSinceOccurrence}" />

I could create a timer in my view model that fires PropertyChanged every second, but there are likely to be many such elements in the UI (its a template for items in an ItemsControl) and I don't want to create that many timers.

My knowledge of animation with storyboards isn't great. Can the WPF animation framework help in this case?

+2  A: 

You could create a single DispatcherTimer statically for your view model, and then have all instances of that view model listen to the Tick event.

public class YourViewModel
{
    private static readonly DispatcherTimer _timer;

    static YourViewModel()
    {
        //create and configure timer here to tick every second
    }

    public YourViewModel()
    {
        _timer.Tick += (s, e) => OnPropertyChanged("SecondsSinceOccurence");
    }
}

HTH, Kent

Kent Boogaart
I was hoping it would have been possible to have an element (or binding) that would pull this periodically, rather than having the underlying data source notifying. Can one create a custom binding and add a `RefreshPeriod` property? If so then DispatcherTimer instances could be pooled too.
Drew Noakes