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

本文关键字:周期 几个 故事 WPF 为什么 | 更新日期: 2023-09-27 18:03:20

我有一个画布,我在上面画矩形,并在故事板的帮助下随机移动它们。几个循环之后,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);
            }
        }
    }

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

如果不创建并移动矩形,Completed事件也不会发生:

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上面说的,我认为使用计时器代替故事板,但也许你有理由使用故事板....

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

你很快就会得到数以万计的矩形,而这些矩形的绘制时间会越来越长。