If no item is selected in the ListBox, then the code works fine.
If at least one item is selected in the ListBox, the foreach iteration breaks after the first item is evaluated. The exception is an InvalidOperationException and the detail shows Items collection has been modified.
foreach (object item in listBoxFiles.Items) //InvalidOperationException occurs
{
if (listBoxFiles.SelectedItems.Contains(item))
{
//do nothing
}
}
Edit: I was looking for something like ListBoxItem.IsSelected but it does not exist.
I can reproduce the problem. The access to
SelectedItemsseems to be changingItems, not the call toContains. It should not do that. I have no explanation at the moment.Workaround:
If you check if
itemis contained inSelectedItemsyou could right away iterate overSelectedItemsinstead. Another alternative would be to copySelectedItemsbefore the iteration like this: