WPF故事板死亡
问题描述:
C#:WPF故事板死亡
public partial class MainWindow : Window
{
Storyboard a = new Storyboard();
int i;
public MainWindow()
{
InitializeComponent();
a.Completed += new EventHandler(a_Completed);
a.Duration = TimeSpan.FromMilliseconds(10);
a.Begin();
}
void a_Completed(object sender, EventArgs e)
{
textblock.Text = (++i).ToString();
a.Begin();
}
}
XAML:
<Window x:Class="Gui.MainWindow" x:Name="control"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<Canvas>
<TextBlock Name="textblock"></TextBlock>
</Canvas>
什么是错的代码? 故事板在20-50回合后停止。每次有不同的号码
答
我相信这是因为在您的代码中Storyboard的动画时钟与TextBlock的Text DependencyProperty之间没有关系。如果我不得不猜测,我会说故事板是什么时候搞出来的,由于弄脏了DependencyProperty(TextBlock.Text是一个DependencyProperty)更新管道,它在一定程度上是随机的。如下创建这样一个关联关系(无论RunTimeline或RunStoryboard将工作,但显示的看着这个替代方法):
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);
}
}
这只要对我的作品的,我会让它运行(〜10长于倍它曾经花光了)否则。
Tim
非常有趣的问题,我发现这停止了,当我的鼠标移过TextBlock我有时得到1500。 – 2008-11-24 21:18:36