iLemming
iLemming

Reputation: 36254

Binding to DateTime.Now. Update the value

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...

Upvotes: 13

Views: 23222

Answers (5)

A P
A P

Reputation: 2548

Adding to this answer, if you want to format the time returned: You can do it via a label as such:

<Label Content="{Binding Source={StaticResource ticker} ,Path=Now, Mode=OneWay}" ContentStringFormat="dd-MM-yyyy HH:mm"/>

and change your ContentStringFormat as you please

Upvotes: 0

myermian
myermian

Reputation: 32525

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

Upvotes: 26

Maksim Satsikau
Maksim Satsikau

Reputation: 1494

Indeed, the 'canonical' way of doing this is to set up a DispatcherTimer

However, you can also do it with a storyboard and a fake converter like so:

    <Storyboard x:Key="clockStory" Duration="0:0:2" RepeatBehavior="Forever">
        <StringAnimationUsingKeyFrames
            Storyboard.TargetName="clock"
            Storyboard.TargetProperty="(Label.Tag)">
            <DiscreteStringKeyFrame KeyTime="0:0:0" Value="Let's force binding" />
            <DiscreteStringKeyFrame KeyTime="0:0:1" Value="..to change back and forth" />
        </StringAnimationUsingKeyFrames>
    </Storyboard>
</Window.Resources>

<Window.Triggers>
    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
        <BeginStoryboard Storyboard="{StaticResource clockStory}"/>
    </EventTrigger>
</Window.Triggers>

<Grid>
    <Label x:Name="clock" Content="{Binding ElementName=clock, Path=Tag, Converter={StaticResource conv}}"/>
</Grid>

..with converter being the following

public class AnythingToCurrentTimeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return DateTime.Now.ToString("HH:mm:ss");
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Enjoy!

Upvotes: 0

aloisdg
aloisdg

Reputation: 23531

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.

Upvotes: 2

SLaks
SLaks

Reputation: 888077

You need to make a timer that updates the textbox every second.

Upvotes: 0

Related Questions