I have a canvas where I draw rectangles and move them randomly with the help of a storyboard. After a few cycles the storyboard.completed event does not fire any more. Does anybody know? here is my 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>
And the code:
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);
}
}
}
The Completed event does also not occur whitout creating and moving rectangles:
If you add a animation to the storyboard, the storyboard not stops firing the event.
Like Kshitij Mehta said above, i think use a timer instead the storyboard, but maybe you have a reason to use a storyboard….