I’ve recently posted a Twitter Client to codeplex.com and I’ve been frustrated that I can’t seem to manually update when the tweet was posted. So I’ve started thinking a came up with this solution.
<p>First create a Model that is derived from INotifyPropertyChanged and create the specific members:
public event PropertyChangedEventHandler PropertyChanged;</p> <p>protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}</p> <p>Define your properties:
private DateTime _timeAgo;
public string TimeAgo
{
get { return _timeAgo.ToRelativeTime(); //TweetSharp Extension }
set
{
_timeAgo = DateTime.Parse(value);
OnPropertyChanged(“TimeAgo”);
}
}</p> <p>Now define a System.Timers.Timer:</p> <p>using System.Timers;
private Timer _timer = new Timer(){ Interval = 30000 //30000 miliseconds = 30 seconds };
private bool TimerFlag = true;</p> <p>Modify your OnPropertyChanged method and add a new method to handle the Timer’s Elapsed event:</p> <p>protected void OnPropertyChanged(string propertyName)
{
if(TimerFlag)
{
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Start();
TimerFlag = false;
}
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
OnPropertyChanged(“TimeAgo”);
}</p> <p>Now I’m not sure how effective is this way but it seems to do the job for me. This only works for this kind of a scenario, because once the Model returns the TimeAgo, WPF’s DataBinding System doesn’t know if the property is changing over time. To it, it’s just a string. In other scenario’s when you change the property WPF’s DataBinding System knows that because of the OnPropertyChanged in set.
Simple, not sure if elegant but definitely works.</p> <p>Can’t wait to hear your opinions on this.</p>