2013-04-29 2 views
0

루프를 기준으로 자식을 주 그리드에 추가 중입니다. 하지만 어떻게 그들을 제거합니까? 함수가 호출 될 때마다 추가 한 자식 만 제거한 다음 새 함수를 추가하려고합니다.C# 루프에 의해 추가 된 자식 제거

void flcl_Selection(object sender, MyEventArgs e) 
    { 
     //remove children here  
     for (int i = 0; i < e.MyFirstString.Count; i ++) 
     { 
      LabelCountry lbl = new LabelCountry((string)e.MyFirstString[i]); 
      MainGrid.Children.Add(lbl); 
     } 
    } 
+0

당신은 당신이 사용하는 플랫폼 이서/프레임 워크를 언급하는 것을 잊었다. –

+0

문제에 대한 의견이 있으십니까? 이 요구 사항을 극복하기 위해 무엇을 시도 했습니까? –

+0

각 lbl 이름을 지정하고 제거하려고했습니다. 그러나 혼란 스러울 수 있으므로 언급하지 않았습니다. MatthiasG의 대답은 내가 찾는 것입니다. – Dim

답변

4

삭제할 수 있도록 추가 된 요소를 저장해야합니다. 예컨대는 :

private List<LabelCountry> addedElements = new List<LabelCountry>(); 

void flcl_Selection(object sender, MyEventArgs e) 
{ 
    //remove old items 
    foreach(LabelCountry element in addedElements) 
    { 
     MainGrid.Children.Remove(element); 
    } 
    addedElements.Clear(); 
    // add new items 
    for (int i = 0; i < e.MyFirstString.Count; i ++) 
    { 
     LabelCountry lbl = new LabelCountry((string)e.MyFirstString[i]); 
     addedElements.Add(lbl) 
     MainGrid.Children.Add(lbl); 
    } 
} 
+1

ㅎ .. 너는 나를 때려. – maxlego

2
private List<object> _addedItems = new List<object>(); 

void flcl_Selection(object sender, MyEventArgs e) 
{ 
    //remove children here  
    foreach(var item in _addedItems) 
    { 
     MainGrid.Children.Remove(item); 
    } 
    _addedItems = new List<object>(); 

    for (int i = 0; i < e.MyFirstString.Count; i ++) 
    { 
     LabelCountry lbl = new LabelCountry((string)e.MyFirstString[i]); 
     MainGrid.Children.Add(lbl); 
     _addedItems.Add(lbl); 
    } 
} 
관련 문제