这个问题与我问的另一个问题相似,但是在那种情况下,我想知道强制绑定从 XAML 或视图模型更新,在这种情况下,我想知道如何将其包装到自定义 WPFFrameworkElement
中。
我所追求的功能是一段文本,表明某件事发生了多久。
<TextBlock Text="It happened " />
<my:AgeTextBlock SinceTime="{Binding OccurredAtUtc}" />
<TextBlock Text=" ago" />
这将呈现为(例如):
发生在 1 分 13 秒前
我有从 a 转换为TimeSpan
显示的人类可读形式的代码。
为了让 UI 每秒更新一次,我正在考虑使用静态DispatcherTimer
(来自Kent Boogaart 的回答的想法)。
所以这就是我所拥有的:
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?
}
评论表明我的问题。我看不出如何用这种方法正确清理。没有Dispose
方法可以覆盖和删除事件处理程序。
这里推荐的模式是什么?