0
votes

I have a ListBox in WPF with a DataBinded Xml Collection. I set the SelectionMode to Extended so the user can select multiple items. I have a RemoveItem command which iterates through the selecteditems and removes them from the list:

   var selecteditems = this.SelectedItems;
   for(int i = 0; i < selecteditems.Count; i++ )
   {
        ItemBox ouritem = (ItemBox)this.ItemContainerGenerator.ContainerFromItem(this.SelectedItems[i]);
         XmlDataProvider prov = this.DataContext as XmlDataProvider;
         XmlNode MainNode = prov.Document.SelectSingleNode("//MainNode");
         MainNode.RemoveChild(selecteditems[i] as XmlNode);

   }

The problem is that after the first item of a selection is deleted, the selection is cleared and the last item of the list is selected.

How can I keep the selection that I started with and make sure all the items are deleted?

2

2 Answers

1
votes

How about the old 'take a copy first' approach?:

IList selectedItems = new List<YourDataType>();
foreach (YourDataType item in this.SelectedItems) selectedItems.Add(item);
for (int index = selectedItems.Count - 1; index >= 0; index--)
{
    // remove each selected item here
}
0
votes

Execute your loop in reverse iteration.

 var selecteditems = this.SelectedItems;
 for(int i = selecteditems.Count-1; i>=0; i-- )
 {
    ItemBox ouritem = (ItemBox)this.ItemContainerGenerator.ContainerFromItem(this.SelectedItems[i]);
     XmlDataProvider prov = this.DataContext as XmlDataProvider;
     XmlNode MainNode = prov.Document.SelectSingleNode("//MainNode");
     MainNode.RemoveChild(selecteditems[i] as XmlNode);

 }