2013-06-19 36 views
1

在我的Windows 8应用程序中,我想在TextBlock元素中显示当前时间。时间值应该每秒更新一次。下面的代码工作正常,但我认为这不完全是理想的解决方案。那么有没有更好的方法来做到这一点?如何将DateTime.Now绑定到TextBlock?

public class Clock : Common.BindableBase { 
    private string _time; 
    public string Time { 
     get { return _time; } 
     set { SetProperty<string>(ref _time, value); } 
    } 
} 

private void startPeriodicTimer() { 
    if (PeriodicTimer == null) { 
     TimeSpan period = TimeSpan.FromSeconds(1); 

     PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer((source) => { 

      Dispatcher.RunAsync(CoreDispatcherPriority.Normal, 
       () => { 
        DateTime time = DateTime.Now; 
        clock.Time = string.Format("{0:HH:mm:ss tt}", time); 
        [...] 
       }); 

     }, period); 
    } 
} 

在LoadState的方法:

clock = new Clock(); 
clock.Time = string.Format("{0:HH:mm:ss tt}", DateTime.Now); 
currentTime.DataContext = clock; 
startPeriodicTimer(); 
+1

使用一个定时器..... –

+0

你应该更频繁地轮询。如果你每秒钟做一次,你可能会发现时钟似乎会出现口吃或跳跃。由于时钟精度和CPU时序问题,“每秒一次”不能保证以* 1秒的间隔*运行。在任何一个方向上都可能是几毫秒。所以设置一个500毫秒的值,它会更平滑。 –

回答

0

的WinRT具有DispatcherTimer类。你可以使用它。

XAML

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

<TextBlock Text="{Binding Source={StaticResource ticker}, Path=Now}" FontSize="20"/> 

C#

public class Ticker : INotifyPropertyChanged 
{ 
    public Ticker() 
    { 
     DispatcherTimer timer = new DispatcherTimer(); 
     timer.Interval = TimeSpan.FromSeconds(1); 
     timer.Tick += timer_Tick; 
     timer.Start(); 
    } 

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

    public string Now 
    { 
     get { return string.Format("{0:HH:mm:ss tt}", DateTime.Now); } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
} 
1

您可以使用一个计时器。

var timer = new Timer { Interval = 1000 }; 
timer.Elapsed += (sender, args) => NotifyPropertyChanged("Now"); 
timer.Start(); 

并且每秒通知一个属性。

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

我在我的应用程序如何做到使用定时器

 private void dispatcherTimer_Tick(object sender, EventArgs e) 
     { 
      TxtHour.Text = DateTime.Now.ToString("HH:mm:ss"); 
     } 
private void MainWindow_OnLoad(object sender, RoutedEventArgs e) 
     { 
      System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer(); 
      dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick); 
      dispatcherTimer.Interval = new TimeSpan(0, 0, 1); 
      dispatcherTimer.Start(); 
      TxtDate.Text = DateTime.Now.Date.ToShortDateString(); 
     }