I have a WPF window that manages sets of configurations and it allows users to edit a configuration set (edit button) and to remove a configuration set (remove button). The
This is because , you are modifying a collection while iterating over it.
if you have binded item source of listbox than try to remove the items from the source
use:
private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
foreach(ConfigSet item in this.configSetListBox.SelectedItems)
{
this.configSetListBox.ItemsSource.Remove(item); // ASSUMING your ItemsSource collection has a Remove() method
}
}
Note: my use of this. is just so it as it is more explicit - it also helps one see the object is in the class namespace as opposed to variable in the method we are in - though it is obvious here.
I Used this logic to preceed. And it worked.
you may want to try it.
private void RemoveSelectedButton_Click(object sender, RoutedEventArgs e) {
if (SelectedSpritesListBox.Items.Count <= 0) return;
ListBoxItem[] temp = new ListBoxItem[SelectedSpritesListBox.SelectedItems.Count];
SelectedSpritesListBox.SelectedItems.CopyTo(temp, 0);
for (int i = 0; i < temp.Length; i++) {
SelectedSpritesListBox.Items.Remove(temp[i]);
}
}
this was answered here already.
WPF - Best way to remove an item from the ItemsSource
You will need to implement an ObservableCollection and then whatever you do to it will be reflected in your listbox.
for (int i = lstAttachments.SelectedItems.Count - 1; i >= 0; i--)
{
lstAttachments.Items.Remove(lstAttachments.SelectedItems[i]);
}
Simplest way to remove items from a list you iterate through is going backwards because it does not affect the index of items you are moving next to.