ListBox Item Removal

2019-02-19 12:02发布

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.

4条回答
时光不老,我们不散
2楼-- · 2019-02-19 12:24

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-19 12:33

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.

查看更多
干净又极端
4楼-- · 2019-02-19 12:34

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

查看更多
smile是对你的礼貌
5楼-- · 2019-02-19 12:36

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]);
        }
    }
查看更多
登录 后发表回答