2011-12-06 111 views
0

我想使用mvvm模式在wpf屏幕中持續更新屏幕上顯示當前時間。使用MVVM在WPF中連續顯示當前時間顯示

我在我的視圖模型

編寫這些代碼和我寫了這個方法

public string GetCurrentDateTime() 
{ 
    try 
    { 
     DispatcherTimer timer = new DispatcherTimer(new TimeSpan(0, 0, 1), 
      DispatcherPriority.Normal, 
      delegate 
      { 
       this.CurrentDateTime = DateTime.Now.ToString("HH:mm:ss"); 
      }, 
      this.Dispatcher); 

      return CurrentDateTime; 
    } 
    catch 
    { 
     return CurrentDateTime; 
    } 
} 

我綁定我的文本塊與屬性,但它正顯示出異常,因爲this.CurrentDateTime爲空。

有什麼建議爲什麼?

+0

保重!當GetCurrentDateTime被調用時,你總是啓動一個新的定時器。 – PVitt

回答

2

我不確定你的意圖是什麼與RaisePropertyChanged(()=> this.CurrentDateTime)。

如果是照顧MVVM屬性改變的通知,那麼這段代碼應該是在你的虛擬機

public event PropertyChangedEventHandler PropertyChanged; 

protected void OnPropertyChanged(string propertyName) 
{ 

    if (PropertyChanged != null) 
     PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
} 

那麼你的設置應該是

set 
{ 
    if (value != _currentDateTime) 
    { 
     _currentDateTime = value; 
     OnPropertyChanged("CurrentDateTime"); 
    } 
} 

不斷更新你的時間,使用一個定時器 http://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.71).aspx

然後,您可以設置間隔說1秒,並在每個計時器已過去的事件設置您的CurrentDat ETIME

CurrentDateTime=DateTime.Now.ToString(); 
+3

我的猜測是RaisePropertyChanged具有簽名RaisePropertyChanged(表達式> propertyExpression),並且正在解析表達式樹以將表達式的右側解析爲字符串屬性名稱。我對我的視圖模型做了同樣的事情,強制在屬性和GUI字符串之間進行早期綁定,從而消除了將屬性名稱信息作爲屬性和魔術字符串重複使用的需要。 –

+0

感謝您的回覆。 – Kanvas

0

我不知道爲什麼這個問題正在發生,但我用這個代碼,但輕微的改變來實現相同的功能。

我改變了代碼GetCurrentDateTime方法的try塊

try 
     { 
      DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer(); 
      dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick); 
      dispatcherTimer.Interval = new TimeSpan(0, 0, 1); 
      dispatcherTimer.Start(); 



      return CurrentDateTime; 
     } 

以及與此我添加了一個新的方法定時器

private void dispatcherTimer_Tick(object sender, EventArgs e) 
    { 
     // Updating the Label which displays the current second 
     this.CurrentDateTime = DateTime.Now.ToString(" HH:mm tt"); 

     // Forcing the CommandManager to raise the RequerySuggested event 
     CommandManager.InvalidateRequerySuggested(); 
    } 

現在正在