WPF C#基于内容删除列表框项

时间:2015-04-21 18:29:06

标签: c# .net wpf listbox

我有一个列表框,我需要根据内容修改列表。我试图这样做,但它没有做任何事情。

string itemRemove =   "Apple";
lstFruits.Items.Remove(itemRemove);

1 个答案:

答案 0 :(得分:2)

问题是在ListBox控件中,您无法删除像List<T>中删除的项目(即使用枚举器)。你必须使用索引循环,从最后一项开始,如下所示:

for (int n = lstFruits.Items.Count - 1; n >= 0; --n)
{
    string itemRemove = "Apple";
    if (lstFruits.Items[n].ToString().Contains(itemRemove))
    {
        lstFruits.Items.RemoveAt(n);
    }
}