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?
Having a timer to periodically trigger
PropertyChanged
event is one way to go. But if you have lots of items in aContentControl
and the property you want to update is in theItemTemplate
of thatContentControl
, that means unnecessarily creating 100+ timers and having them raisePropertyChanged
all at the same time. However, this behavior will still be created for every item when used in anItemsControl
likeListBox
.For this reason I created this Behavior that will only be created once for every binding in your Template. It's also purely MVVM.
Usage
Dependencies
Note that http://schemas.microsoft.com/expression/2010/interactivity namespace is available under a NuGet package called
System.Windows.Interactivity.WPF
. It will also be automatically added if you open the project in blend.Copy and paste code
You could create a single
DispatcherTimer
statically for your view model, and then have all instances of that view model listen to theTick
event.