问题描述
我有一个管理配置集的 WPF 窗口,它允许用户编辑配置集(编辑按钮)和删除配置集(删除按钮).该窗口有一个 ListBox 控件,该控件按名称列出配置集,其 ItemsSource 具有与配置集列表的绑定集.
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 window has a ListBox control that lists the configuration sets by name and its ItemsSource has a binding set to a list of configuration sets.
我正在尝试删除窗口代码隐藏文件中的项目..
I'm trying to remove the item in the code behind file for the window..
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 :)
My code yields an invalid operation exception stating "Access and modify elements with ItemsControl.ItemsSource instead." What property should I be accessing to properlyremove items from the ListBox? Or is there possibly a more elegant way to handle this in WPF? My implementation is a bit WinForm-ish if you will :)
解决方案
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 不会更新;所以这是我的解决方案所必需的.
In my case I had a List as the ItemSource binding type so I had to cast it that way. Without refreshing the Items collection, the ListBox doesn't update; so that was necessary for my solution.
推荐答案
使用:
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.
这篇关于列表框项删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!