在Silverlight中以编程方式删除元素

时间:2010-05-12 15:23:58

标签: c# silverlight-3.0

我开始学习银光并练习我正在做一个简单的太空入侵者输入视频游戏。

我的问题是我正在以编程方式创建自定义控件(项目符号):

if(shooting)
{
    if(currBulletRate == bulletRate)
    {
        Bullet aBullet = new Bullet();

        aBullet.X = mouse.X - 5;
        aBullet.Y = mouse.Y - Ship.Height;
        aBullet.Width = 10;
        aBullet.Height = 40;
        aBullet.Tag = "Bullet";

        LayoutRoot.Children.Add(aBullet);

        currBulletRate = 0;
    }
    else
        currBulletRate++;
}

然而,一旦他们离开边界我就无法移除它们(离开LayoutRoot)。

我尝试在LayoutRoot.Children中循环并删除,但我似乎无法正确使用。

1 个答案:

答案 0 :(得分:2)

UIElement[] tmp = new UIElement[LayoutRoot.Children.Count];             
LayoutRoot.Children.CopyTo(tmp, 0);  

foreach (UIElement aElement in tmp)
{
    Shape aShape = aElement as Shape; 

    if (aShape != null && aShape.Tag != null)
    {

        if (aShape.Tag.ToString().Contains("Bullet"))
        {
            if (Canvas.GetTop(aShape) + aShape.ActualHeight < 0) // This checks if it leaves the top
            {
                LayoutRoot.Children.Remove(aElement);
            }
            else if(Canvas.GetTop(aShape) > Canvas.ActualHeight) // This condition checks if it leaves the bottom
            {
                LayoutRoot.Children.Remove(aElement);
            }
        }
    }
}

您粘贴的代码只是检查子弹是否离开画布顶部。

相关问题