如何有一个WPF绑定更新每一秒? [英] How to have a WPF binding update every second?

查看:133
本文介绍了如何有一个WPF绑定更新每一秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要显示多少秒是如何顺利通过,因为一些事件发生的用户。从概念上讲,我认为模型具有这样的特性:

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; }
}

如果我绑定一个 TextBlock.Text 属性 SecondsSinceOccurrence ,该值显示,但它是静态的。时间的流逝并没有反映这一事件的年龄增加。

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}" />

我可以在我的视图模型创建一个定时器触发的PropertyChanged 每一秒,但也有可能是在UI很多这样的元件(其对项目的模板一个的ItemsControl ),我不希望创建许多定时器。

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.

我的故事板动画方面的知识不是很大。可在这种情况下,WPF动画框架帮助?

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

推荐答案

您可以创建一个 DispatcherTimer 静态为您的视图模型,然后有看法的所有实例模型听勾选事件。

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");
    }
}

这篇关于如何有一个WPF绑定更新每一秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆