2014-09-29 72 views
1

嘗試格式化更改應用程序資源時發生更改的類中的返回值。活動時鐘的格式問題

這裏是我的代碼:

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格式化爲我想要的格式?

回答

3

由於您綁定了formated屬性,因此在Now上提高更改通知將不會強制綁定更新。因此在更改值後,在formated上引發更改通知,綁定可能會將其更新爲UI。

變化

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

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

噢...,謝謝!我認爲那是在做別的事情!大聲笑 – 2014-09-29 14:40:04

+1

@MartynBall,當你在'現在'上使用轉換器時,有必要提高通知。但是您的方法是使用其他屬性來執行格式設置,因此需要更改綁定屬性的通知而不是源屬性。最後但並非最不幸的編碼:) – pushpraj 2014-09-29 14:44:06