0

我正在将孩子循环添加到主网格。但是我该如何删除它们?我只想删除每次调用函数时添加的子项,然后添加新的子项。

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

2 回答 2

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);
    }
}
于 2013-04-29T07:25:10.017 回答
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);
    }
}
于 2013-04-29T07:25:47.840 回答