简体   繁体   English

通过 ListBox.Items 进行交互时的异常

[英]Exception when Interating through ListBox.Items

If no item is selected in the ListBox, then the code works fine.如果在 ListBox 中没有选择任何项目,则代码工作正常。

If at least one item is selected in the ListBox, the foreach iteration breaks after the first item is evaluated.如果在 ListBox 中至少选择了一项,则在评估第一项后 foreach 迭代会中断。 The exception is an InvalidOperationException and the detail shows Items collection has been modified.异常是 InvalidOperationException,详细信息显示 Items 集合已被修改。

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.编辑:我正在寻找类似ListBoxItem.IsSelected 的东西,但它不存在。

I can reproduce the problem.我可以重现这个问题。 The access to SelectedItems seems to be changing Items , not the call to Contains .SelectedItems的访问似乎正在改变Items ,而不是对Contains的调用。 It should not do that.它不应该那样做。 I have no explanation at the moment.我暂时没有解释。

Workaround:解决方法:

If you check if item is contained in SelectedItems you could right away iterate over SelectedItems instead.如果您检查item是否包含在SelectedItems您可以立即迭代SelectedItems Another alternative would be to copy SelectedItems before the iteration like this:另一种选择是在迭代之前复制SelectedItems ,如下所示:

List<object> selectedItems = new List<object>();
selectedItems.AddRange( listBoxFiles.SelectedItems.OfType<object>() );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM