首页 > 解决方案 > WPF C# 无法从 Listview 中删除项目(ItemsSource 正在使用中)

问题描述

我有一个列表视图,我想在执行某些后台任务后从中删除项目。在我的 background_dowork 中,我称之为:

this.Dispatcher.Invoke(new MethodInvoker(delegate ()
{
    FilesList.Items.RemoveAt(FilesList.Items.IndexOf(selectedFile));
    FilesList.UpdateLayout();
}));

selectedFile 是 FilesList 中的一个项目。

但是,当调度程序运行时,我收到 itemsource 正在使用的异常?

如何从列表中删除项目?

这就是我创建 FilesList 的方式:

InputFile inputItem = new InputFile
{
    FileName = f[i].Name,
    FilePath = f[i].FullName
};
lif.Add(inputItem);
FilesList.ItemsSource = lif;

标签: c#.netwpf

解决方案


您应该从 中删除该项目ItemsSource

var itemsSource = FilesList.ItemsSource as IList<YourClass>();
if (itemsSource != null)
    itemsSource.Remove(selectedFile);

请注意,您需要将 设置ItemsSource为 aObservableCollection<T>或实现的自定义集合INotifyCollectionChanged,以便将其从视图中删除,而无需显式刷新它,即从 a 中删除项目List<T>不会更新视图。


推荐阅读