我有一个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式的:)
解
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不会更新。因此这对于我的解决方案是必要的。
最佳答案
使用:
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
}
}
注意:我使用这个。只是这样,因为它更加明确-也可以帮助我们看到对象在类名称空间中,而不是我们所使用的方法中的变量-尽管在这里很明显。
关于c# - 列表框项目删除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4378099/