2010-05-12 43 views
0

我開始學習silverlight並且練習我正在做一個簡單的太空入侵者類型的視頻遊戲。在Silverlight中以編程方式去除元素

我的問題,我創建自定義控件(子彈)編程就像這樣:

 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並刪除,但我似乎無法得到它的權利。

任何有識之士將不勝感激!

+0

是您的LayoutRoot一個畫布? 它們是否在視覺範圍之外應該沒有關係。 也許向我們展示一些xaml 並刪除代碼:D – TimothyP 2010-05-12 15:46:56

+0

我想刪除它們的原因是,所以他們不停留在周圍,並降低性能。呃...試圖弄清楚如何粘貼代碼。 D: – Mayo 2010-05-12 16:24:37

回答

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); 
      } 
     } 
    } 
} 

您粘貼的代碼只是檢查子彈是否離開畫布的頂部。

+0

好吧,我設法讓它工作。子彈正在被移除,但是......現在它創造了很多開銷,使得它每次必須移除控件時都很慢。 – Mayo 2010-05-14 13:44:01

+0

Nvm我最後的評論。我現在明白了爲什麼LayoutRoot.Children中的元素被複制到UIElements的臨時數組中。顯然直接通過LayoutRoot中的孩子循環太慢。我嘗試通過刪除這部分來簡化代碼,但是將其添加回來解決了我的問題。 感謝您的幫助! – Mayo 2010-05-14 13:50:05

+0

如果這解決了您的問題,請接受它作爲答案 – Stephan 2010-05-17 13:21:05

相關問題