2011-11-07 168 views
0

我如何能在multiselectlist刪除項目7

刪除的項目我的代碼的工作無法正常

   for (int i = MyListBox.Items.Count - 1; i >= 0; i--) 
       //for (int i = -1; i <= MyListBox.Items.Count; i++) 
       { 
        if (MyListBox.IsSelectionEnabled == true) 
        { 
         MyObservable.RemoveAt(i); 
        } 
       } 

MyListBox:multiSelectList

MyObservable:的ObservableCollection <>

回答

0

您無法刪除這些項目,因爲您在嘗試使用該集合時正在更改該集合。您需要收集要刪除的項目,然後刪除它們,然後刪除它們:

  ICollection<Item> selectedItems = new List<Item>(MyListBox.SelectedItems.Count); 
     foreach (var item in MyListBox.SelectedItems) 
     { 
      Item myItem = item as Item; 
      if (myItem == null) continue; 

      selectedItems.Add(myitem); 
     } 
     foreach (var item in selectedItems) 
     { 
      MyObservable.Remove(item); 
     } 
     MyListBox.IsSelectionEnabled = false;