ListBox中删除项 [英] ListBox Item Removal
问题描述
我有一个管理组配置的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而不是元素。我应该是什么性质的访问,以properlyremove从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绑定类型,所以我不得不投这种方式。无刷新项集合,列表框不更新; 。所以这是必要我的解决方案
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.
这篇关于ListBox中删除项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!