2010-07-28 15 views
11

Bueno, necesitaba para unirse a un DateTime.Now TextBlock, he usado:Enlace a DateTime.Now. Modificar el valor

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

Ahora, la forma de forzarlo a actualizar? Se consigue es el momento en que se carga el control y no actualizarlo ...

Respuesta

21

Editado (No dar cuenta de lo que quieren de actualización automática):

Aquí es a link de una clase 'ticker' que usa INotifyPropertyChanged para que se actualice automáticamente. Aquí está el código del sitio:

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

declaran:

xmlns:sys="clr-namespace:System;assembly=mscorlib" 

Ahora bien, esto va a funcionar:

<TextBox Text="{Binding Source={StaticResource ticker}, Path=Now, Mode=OneWay}"/> 
+2

Incorrecto. Esto no ayudará. (Esto es exactamente lo que escribió) – SLaks

+0

¿Y por qué no funciona? –

+0

Porque todavía no se actualizará. Lee la pregunta nuevamente – SLaks

1

Necesitas hacer un contador de tiempo que las actualizaciones el cuadro de texto cada segundo.

2

para Windows Phone, puede utilizar este fragmento

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; 

adapté el código de m-y. Espero que este también sea útil.

Cuestiones relacionadas