2010-07-28 44 views
11

好吧,我需要DateTime.Now綁定到一個TextBlock,我用的是:綁定到DateTime.Now。更新價值

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

現在,如何迫使它更新?它得到的,當控件加載並不會更新它的時候......

回答

21

編輯(我沒有考慮他想自動更新):

這裏的「北京時間」類的a link那使用INotifyPropertyChanged,所以它會自動更新。下面是從網站的代碼:

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

錯了。這不會幫助。 (這正是他寫的) – SLaks 2010-07-28 16:01:26

+0

爲什麼不行? – 2010-07-28 16:02:40

+0

因爲它仍然不會更新。再次閱讀問題。 – SLaks 2010-07-28 16:04:45

1

你需要做一個計時器,更新每秒一次的文本框。

2

對於Windows手機,就可以使用這個片段

public Timer() 
{ 
    DispatcherTimer timer = new DispatcherTimer(); 
    timer.Interval = TimeSpan.FromSeconds(1); // 1 second updates 
    timer.Tick += timer_Tick; 
    timer.Start(); 
} 

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

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

public event PropertyChangedEventHandler PropertyChanged; 

我適應M-y的代碼。希望這個也能有用。