This is a follow up based on the answer of a previous question. I've managed to come up with a DependencyProperty which will be updated using a Timer to always have the latest date time, and a textblock which shows the datetime. Since it's a DependencyProperty, whenever the timer updates the value, the textblock will show the latest DateTime as well.
The dependency object
public class TestDependency : DependencyObject
{
public static readonly DependencyProperty TestDateTimeProperty =
DependencyProperty.Register("TestDateTime", typeof(DateTime), typeof(TestDependency),
new PropertyMetadata(DateTime.Now));
DispatcherTimer timer;
public TestDependency()
{
timer = new DispatcherTimer(new TimeSpan(0,0,1), DispatcherPriority.DataBind, new EventHandler(Callback), Application.Current.Dispatcher);
timer.Start();
}
public DateTime TestDateTime
{
get { return (DateTime)GetValue(TestDateTimeProperty); }
set { SetValue(TestDateTimeProperty, value); }
}
private void Callback(object ignore, EventArgs ex)
{
TestDateTime = DateTime.Now;
}
}
The Window Xaml
<Window.DataContext>
<local:TestDependency/>
</Window.DataContext>
<Grid>
<TextBlock Text="{Binding TestDateTime}" />
</Grid>
This works very well, but i'm wondering, what do I have to do if I wanna format the time string in a different way, is there a way to call a ToString(formatter)
on the date time before displaying it in the textblock, while maintaining the ability to auto update the textblock using the DependencyProperty? What is the correct way to do this in code behind, and the correct way to do this in Xaml, if it's even possible?
And, if I have Multiple textboxes to show, each with a different date time format, what is the proper way to make use of only 1 timer to display all the different date time formats in different textboxes, do I have to create a DependencyProperty for each single format?