c# - 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;
解决方案
您应该从 中删除该项目ItemsSource
:
var itemsSource = FilesList.ItemsSource as IList<YourClass>();
if (itemsSource != null)
itemsSource.Remove(selectedFile);
请注意,您需要将 设置ItemsSource
为 aObservableCollection<T>
或实现的自定义集合INotifyCollectionChanged
,以便将其从视图中删除,而无需显式刷新它,即从 a 中删除项目List<T>
不会更新视图。
推荐阅读
- python-2.7 - 无全局变量传递;退货问题
- go - 如何通过 go generate 传递参数
- python - 从同一个列表中查找项目对的数量?
- react-native - TypeError: _rxjs.Observable.fromPromise 不是函数
- java - 正则表达式:带分隔线模式的多行
- java - 如何创建大小为 BigInteger 的数组或数组列表。我需要一个真正的大数组
- windows - 在 SSD 上安装 Windows 10 错误:“我们无法创建新分区...”
- python - 在 Pandas 中结合屏蔽和索引
- javascript - 反应 + Firebase + Python
- php - 如何按照用户 ID 获取 PHP 中 MySQL 列的总和?