I am implementing a countdown timer. I have a TextBlock which is showing the time, using DispatcherTimer.
I would like to create an animation for that TextBlock‘s FontSize property. I want its value to increase to 300pt at the point the timer shows 9pm. So, it starts with FontSize 8pt whenever the application is run and it keeps increasing and when the real time hits 9pm the FontSize should be 300pt.
Here’s how I pictured it: Once the application is run, it will calculate the number of seconds it takes from that moment to get to 9pm; the result will be the stored by the variable timeToGetTo9pm. The problem I am facing is that when I create an animation in XAML, I don’t know how to set timeToGetTo9pm to the animation Duration property.
Any ideas? Also, if my approach is stupid or confusing, please feel free to recommend a better one. Thanks.
Delegate body:
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
DateTime currentTime;
double timeToNewYearInMiliseconds;
currentTime = DateTime.Now;
//targetTime is a DateTime object set elsewhere,
//It represents the 9pm mentioned in the question body
if (DateTime.Compare(targetTime, currentTime) > 0)
{
timeToNewYearInMiliseconds = targetTime.Subtract(currentTime).TotalMilliseconds;
percent = 100 / timeToNewYearInMiliseconds;
PercentageComplete = percent;
}
}
Why not have a ‘TimerFontSize’ property in your ViewModel\Code-Behind and bind the TextBox’s FontSize to it.
As your timer ticks, re-calculate the font size and set the ‘TimerFontSize’ property. If you have implemented INotifyPropertyChanged for ‘TimerFontSize’ the TextBox binding will automatically update and change the size of the font.
This pattern will use your timer, plus data-binding, to drive the animation.
Update
I see what you mean re. separating visual representation from data representation. My suggestion is the easy way. You could clean it up by making the exposed property an elapsed time or countdown value, and then use a ValueConverter to get a FontSize. This would separate data and view concepts.
Here’s a code example of exposing a property in your code-behind. Simply use the binding I previously detailed to hook it up. Ideally you would refactor the code into a ViewModel class rather than have it in the code-behind, just taking things one step-at-a-time.
Update 2
And to separate model representation from view representation use a ValueConverter, e.g.:
Binding:
ValueConverter:
Code-Behind: