Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to DateTime.Now. Update the value

Tags:

binding

wpf

Well, I needed to bind DateTime.Now to a TextBlock, I used that:

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

Now, how to force it to update? It get's the time when control is loaded and wouldn't update it...

like image 347
iLemming Avatar asked Jul 28 '10 15:07

iLemming


2 Answers

Here's a link of a 'Ticker' class that uses INotifyPropertyChanged so it'll auto-update. Here's the code from the site:

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

Declare:

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

Now this will work:

<TextBox Text="{Binding Source={StaticResource ticker}, Path=Now, Mode=OneWay}"/>
like image 105
myermian Avatar answered Nov 14 '22 18:11

myermian


For Windows Phone, you can use this snippet

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;

I adapted the code of m-y. Hope this one can be useful too.

like image 31
aloisdg Avatar answered Nov 14 '22 17:11

aloisdg