This question is similar to another one I asked, but whereas in that case I wanted to know about forcing a binding to update from XAML or a view model, in this case I'd like to know about wrapping this up into a custom WPF FrameworkElement
.
The functionality I'm after is a span of text that indicates how long ago something happened.
<TextBlock Text="It happened " />
<my:AgeTextBlock SinceTime="{Binding OccurredAtUtc}" />
<TextBlock Text=" ago" />
This would render as (for example):
It happened 1 min 13 sec ago
I have code that converts from a TimeSpan
to the human-readable form shown.
In order to have the UI update every second I'm considering using a static DispatcherTimer
(idea from Kent Boogaart's answer).
So here's what I have:
public class AgeTextBlock : TextBlock
{
private static readonly DispatcherTimer _timer;
static AgeTextBlock()
{
_timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
}
public AgeTextBlock()
{
_timer.Tick += ...;
}
// How can I unsubscribe from the Tick event to avoid a memory leak?
}
The comment indicates my problem. I can't see how I'd clean up properly with this approach. There's no Dispose
method to override and remove the event handler.
What is the recommended pattern here?