我在WPF中有一个带有DataBinded Xml Collection的ListBox。我将SelectionMode设置为Extended,以便用户可以选择多个项目。我有一个RemoveItem命令,它遍历selecteditems并从列表中删除它们:
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);
}
问题是删除选择的第一项后,清除选择并选择列表的最后一项。
如何保留我开始的选择并确保删除所有项目?
答案 0 :(得分:1)
旧的'先复制'方法怎么样?:
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
}
答案 1 :(得分:0)
以反向迭代执行循环。
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);
}