为什么WPF故事板在几个周期后会停止?

时间:2011-07-23 08:42:41

标签: c# wpf storyboard

我有一个画布,我绘制矩形并在故事板的帮助下随机移动它们。经过几个周期后,storyboard.completed事件不再激活。有人知道吗?这是我的xaml:

    <Grid>
        <Canvas Name="movingCanvas" Background="Green" Margin="0,29,0,0"></Canvas>
        <TextBlock Height="23" Name="textBlock1" Text="TextBlock" Margin="528,0,0,538" />
    </Grid>

代码:

 private Random random = new Random();
    private Storyboard gameLoop = new Storyboard();
    private int i = 0;

    public Window3()
    {
        InitializeComponent();
        this.gameLoop.Duration = TimeSpan.FromMilliseconds(100);
        this.gameLoop.Completed += new EventHandler(this.gameLoop_Completed);
        this.gameLoop.Begin();
    }

    private void gameLoop_Completed(object sender, EventArgs e)
    {
        this.addRectangle();
        this.moveRectangle();
        i++;
        this.textBlock1.Text = i.ToString();
        this.gameLoop.Begin();
    }

    private void addRectangle()
    {
        Rectangle rect = new Rectangle();
        rect.Height = 100;
        rect.Width = 100;
        rect.Stroke = new SolidColorBrush(Colors.Black);
        Canvas.SetLeft(rect, random.Next((int)this.Width));
        Canvas.SetTop(rect, random.Next((int)this.Height));
        this.movingCanvas.Children.Add(rect);
    }

    private void moveRectangle()
    {
        foreach (UIElement elm in this.movingCanvas.Children)
        {
            int moveLeft = random.Next(10);
            int distance = random.Next(-10, 20);
            if (moveLeft > 5)
            {
                Canvas.SetTop(elm, Canvas.GetTop(elm) + distance);
            }
            else
            {
                Canvas.SetLeft(elm, Canvas.GetLeft(elm) + distance);
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

你真的想在循环的每次迭代中添加一个新的矩形吗?

如果不是数百万的矩形,你很快就会得到成千上万的矩形,这需要更长的时间来绘制。

答案 1 :(得分:1)

完成事件也不会在创建和移动矩形时发生:

private Storyboard gameLoop = new Storyboard();    
private int i = 0;    
public Window3()    
{        
    InitializeComponent();        
    this.gameLoop.Duration = TimeSpan.FromMilliseconds(100);        
    this.gameLoop.Completed += new EventHandler(this.gameLoop_Completed);
    this.gameLoop.Begin();    
}    

private void gameLoop_Completed(object sender, EventArgs e)    
{        
    i++;        
    this.textBlock1.Text = i.ToString();        
    this.gameLoop.Begin();    
}

如果您向故事板添加动画,则故事板不会停止触发事件。

public Window3()    
{        
    InitializeComponent();        
    this.gameLoop.Duration = TimeSpan.FromMilliseconds(100);        
    this.gameLoop.Completed += new EventHandler(this.gameLoop_Completed);
    DoubleAnimation animation= new DoubleAnimation { From = 100, To = 101 };
    ani.SetValue(Storyboard.TargetProperty, this);
    ani.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath("Height"));            
    this.gameLoop.Children.Add(ani);

    this.gameLoop.Begin();    
}    

就像Kshitij Mehta上面所说,我认为使用计时器代替故事板,但也许你有理由使用故事板......