使用实时时钟格式化问题

时间:2014-09-29 14:34:15

标签: c# wpf

尝试从更改应用程序资源的类中格式化返回的值。

这是我的代码:

public class NotifyingDateTime : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private DateTime _now;

    public NotifyingDateTime()
    {
        _now = DateTime.Now;
        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromMilliseconds(2000);
        timer.Tick += new EventHandler(timer_Tick);
        timer.Start();
    }
    public string formated
    {
        get 
        { 
            DateTime datenow = Now;
            //Format the datatime
            string format = "dd MMM, yyyy - h:mm:s tt";
            string formatted = datenow.ToString(format);
            return formatted;
        }
    }
    public DateTime Now
    {
        get { return _now; }
        private set
        {
            _now = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Now"));
        }
    }
    void timer_Tick(object sender, EventArgs e)
    {
        Now = DateTime.Now;
    }
}

这是应用程序资源中的绑定:

{Binding Source={StaticResource NotifyingDateTime}, Path=formated}

首次运行应用程序时,格式化工作正常,但由于我引用formated而不是Now,绑定不会注意到更新,因为这发生在Now

最好的方法是什么?如何让Ticker更新应用程序资源,并将当前DateTime格式化为我想要的格式?

1 个答案:

答案 0 :(得分:3)

因为您已将formated属性绑定,因此在Now上提出更改通知不会强制更新绑定。因此,在更改值后,在formated上提出更改通知,绑定可能会将其更新为UI。

更改

PropertyChanged(this, new PropertyChangedEventArgs("Now")); 

PropertyChanged(this, new PropertyChangedEventArgs("formated"));