ListBox Item Removal

2019-02-19 11:47发布

问题:

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 window has a ListBox control that lists the configuration sets by name and its ItemsSource has a binding set to a list of configuration sets.

I'm trying to remove the item in the code behind file for the window..

private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
    var removedItems = configSetListBox.SelectedItems;

    foreach(ConfigSet removedItem in removedItems)
    {
        configSetListBox.Items.Remove(removedItem);
    }
}

My code yields an invalid operation exception stating "Access and modify elements with ItemsControl.ItemsSource instead." What property should I be accessing to properlyremove items from the ListBox? Or is there possibly a more elegant way to handle this in WPF? My implementation is a bit WinForm-ish if you will :)

Solution

private void RemoveButton_Click(object sender, RoutedEventArgs e)
{   
    foreach(ConfigSet removedItem in configSetListBox.SelectedItems)
    {
        (configSetListBox.ItemsSource as List<ConfigSet>).Remove(removedItem);
    }
    configSetListBox.Items.Refresh();
}

In my case I had a List as the ItemSource binding type so I had to cast it that way. Without refreshing the Items collection, the ListBox doesn't update; so that was necessary for my solution.

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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]);
        }
    }