WPF动画故事板死亡问题

4

C#:

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轮后停止。每次停止的轮数都不同。

非常有趣的问题,我发现当我的鼠标移动到TextBlock上时,有时会停止,并且我得到1500。 - Jobi Joy
1个回答

2

我认为这是因为您的代码没有在Storyboard动画时钟和TextBlock的Text DependencyProperty之间创建关联。如果我猜测的话,当Storyboard崩溃时,由于损坏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倍),就不会出问题了。 蒂姆

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接