I believe it's because with your code there is no relation created between the Storyboard's animation clock and the TextBlock's Text DependencyProperty. if I had to guess I would say when the Storyboard was conking out, it was at a somewhat random time due to fouling the DependencyProperty (TextBlock.Text is a DependencyProperty) update pipeline. Creating such an association as below (either RunTimeline or RunStoryboard will work, but show alternate methods of looking at this):
public partial class Window1 : Window
{
Storyboard a = new Storyboard();
StringAnimationUsingKeyFrames timeline = new StringAnimationUsingKeyFrames();
DiscreteStringKeyFrame keyframe = new DiscreteStringKeyFrame();
int i;
public Window1()
{
InitializeComponent();
//RunTimeline();
RunStoryboard();
}
private void RunTimeline()
{
timeline.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath("(TextBlock.Text)"));
timeline.Completed += timeline_Completed;
timeline.Duration = new Duration(TimeSpan.FromMilliseconds(10));
textblock.BeginAnimation(TextBlock.TextProperty, timeline);
}
private void RunStoryboard()
{
timeline.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath("(TextBlock.Text)"));
a.Children.Add(timeline);
a.Completed += a_Completed;
a.Duration = new Duration(TimeSpan.FromMilliseconds(10));
a.Begin(textblock);
}
void timeline_Completed(object sender, EventArgs e)
{
textblock.Text = (++i).ToString();
textblock.BeginAnimation(TextBlock.TextProperty, timeline);
}
void a_Completed(object sender, EventArgs e)
{
textblock.Text = (++i).ToString();
a.Begin(textblock);
}
}
This works for me for as long as I would let it run (~10 times longer than it ever took to conk out otherwise).
Tim