ListBox Item Removal

女生的网名这么多〃 提交于 2019-12-01 11:24:58

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.

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

phillip

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!