绑定到DateTime.Now。更新值 [英] Binding to DateTime.Now. Update the value

查看:630
本文介绍了绑定到DateTime.Now。更新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我需要DateTime.Now绑定到一个TextBlock,我使用的:

Well, I needed to bind DateTime.Now to a TextBlock, I used that:

 Text="{Binding Source={x:Static System:DateTime.Now},StringFormat='HH:mm:ss tt'}"

现在,如何强制它更新?它得到的时间当控件加载并且不会更新...

Now, how to force it to update? It get's the time when control is loaded and wouldn't update it...

推荐答案

编辑(我没有考虑他想自动更新):

Edited (I didn't account for him wanting to auto-update):

下面的使用INotifyPropertyChanged的所以它会自动更新一个'北京时间'类的链接。下面是从网站的code:

Here's a link of a 'Ticker' class that uses INotifyPropertyChanged so it'll auto-update. Here's the code from the site:

namespace TheJoyOfCode.WpfExample
{
    public class Ticker : INotifyPropertyChanged
    {
        public Ticker()
        {
            Timer timer = new Timer();
            timer.Interval = 1000; // 1 second updates
            timer.Elapsed += timer_Elapsed;
            timer.Start();
        }

        public DateTime Now
        {
            get { return DateTime.Now; }
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Now"));
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}


<Page.Resources>
   <src:Ticker x:Key="ticker" />
</Page.Resources>

<TextBox Text="{Binding Source={StaticResource ticker}, Path=Now, Mode=OneWay}"/>


声明:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

现在,这将工作:

<TextBox Text="{Binding Source={StaticResource ticker}, Path=Now, Mode=OneWay}"/>

这篇关于绑定到DateTime.Now。更新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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