ListBox Item Removal

后端 未结 5 1428
长发绾君心
长发绾君心 2021-01-14 19:15

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

相关标签:
5条回答
  • 2021-01-14 19:58

    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

    0 讨论(0)
  • 2021-01-14 20:09

    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.

    0 讨论(0)
  • 2021-01-14 20:13

    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]);
            }
        }
    
    0 讨论(0)
  • 2021-01-14 20:14

    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.

    0 讨论(0)
  • 2021-01-14 20:16
    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.

    0 讨论(0)
提交回复
热议问题