我有一个WPF窗口来管理多组配置,它允许用户编辑配置集(编辑按钮)并删除配置集(删除按钮)。该窗口有一个ListBox控件,按名称列出配置集,其ItemsSource的绑定设置为配置集列表。
我正在尝试删除窗口代码隐藏文件中的项目..
private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
var removedItems = configSetListBox.SelectedItems;
foreach(ConfigSet removedItem in removedItems)
{
configSetListBox.Items.Remove(removedItem);
}
}
我的代码产生一个无效的操作异常,指出“使用ItemsControl.ItemsSource访问和修改元素”。我应该从ListBox访问哪些属性正确删除项目?或者在WPF中可能有更优雅的方式来处理这个问题?如果您愿意,我的实现有点WinForm-ish。)
解决方案
private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
foreach(ConfigSet removedItem in configSetListBox.SelectedItems)
{
(configSetListBox.ItemsSource as List<ConfigSet>).Remove(removedItem);
}
configSetListBox.Items.Refresh();
}
在我的情况下,我有一个List作为ItemSource绑定类型,所以我不得不这样投出它。在不刷新Items集合的情况下,ListBox不会更新;所以这对我的解决方案来说是必要的。
答案 0 :(得分:3)
使用:
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
}
}
注意:我使用这个。就像它更明确一样 - 它也有助于人们看到对象在类名称空间中而不是我们所处方法中的变量 - 虽然这里很明显。
答案 1 :(得分:1)
这是因为,您正在迭代它时修改集合。
如果你有列表框的绑定项目源,而不是尝试从源中删除项目
答案 2 :(得分:0)
这已在这里得到解答。
WPF - Best way to remove an item from the ItemsSource
你需要实现一个ObservableCollection,然后你对它做的任何事情都会反映在你的列表框中。
答案 3 :(得分:0)
我使用了这个逻辑。它起作用了。
你可能希望尝试
。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]);
}
}
答案 4 :(得分:0)
for (int i = lstAttachments.SelectedItems.Count - 1; i >= 0; i--)
{
lstAttachments.Items.Remove(lstAttachments.SelectedItems[i]);
}
从迭代遍历的列表中删除项目的最简单方法是向后移动,因为它不会影响要移动到其旁边的项目的索引。