reference Removing FrameworkElements on Animation Completion
In above question, how come we access 'myrect' in lambda expression but can't access in traditional method.
lambda expression :
SB.Completed += (s,e) => myCanvas.Children.Remove(myRect);
traditional approach :
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
lastFire = DateTime.Now;
}
DateTime lastFire;
private void myCanvas_MouseMove(object sender, MouseEventArgs e)
{
DateTime nowTime = DateTime.Now;
TimeSpan T = nowTime.Subtract(lastFire);
if (T.TotalMilliseconds > 200)
{
lastFire = nowTime;
Random Rand = new Random();
Rectangle myRect = (Rectangle)FindResource("MyRect");
myRect.Fill = new SolidColorBrush(Color.FromRgb((byte)Rand.Next(256), (byte)Rand.Next(256), (byte)Rand.Next(256)));
Point myLoc = e.GetPosition(myCanvas);
Canvas.SetLeft(myRect, myLoc.X - 10);
Canvas.SetTop(myRect, myLoc.Y - 10);
myCanvas.Children.Add(myRect);
Storyboard SB = (Storyboard)FindResource("GrowSquare");
SB.Completed += new EventHandler(SB_Completed);
SB.Begin(myRect);
}
}
void SB_Completed(object sender, EventArgs e)
{
myCanvas.Children.RemoveAt(0);
}
}
SB_Completed, that's because it's out of scope there. You can pass it to the event handler by creating your own customEventArgsand create anEvenHandler<CustomEventArgs>.