簡體   English   中英

通過 ListBox.Items 進行交互時的異常

[英]Exception when Interating through ListBox.Items

如果在 ListBox 中沒有選擇任何項目,則代碼工作正常。

如果在 ListBox 中至少選擇了一項,則在評估第一項后 foreach 迭代會中斷。 異常是 InvalidOperationException,詳細信息顯示 Items 集合已被修改。

foreach (object item in listBoxFiles.Items) //InvalidOperationException occurs
{
    if (listBoxFiles.SelectedItems.Contains(item)) 
    {
        //do nothing
    }
}

編輯:我正在尋找類似ListBoxItem.IsSelected 的東西,但它不存在。

我可以重現這個問題。 SelectedItems的訪問似乎正在改變Items ,而不是對Contains的調用。 它不應該那樣做。 我暫時沒有解釋。

解決方法:

如果您檢查item是否包含在SelectedItems您可以立即迭代SelectedItems 另一種選擇是在迭代之前復制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