WPF C# 根据内容删除列表框项目

WPF C# delete listbox item based on content

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

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

问题是在 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);
    }
}